C++ 使用ifstream dosen';读取大型二进制文件;t填充字符缓冲区C++;
我正在尝试构建一个小型开源Web服务器,这段代码适用于大型文本文件,如.mp3s/.flac/binary(我尝试发送“cat”)C++ 使用ifstream dosen';读取大型二进制文件;t填充字符缓冲区C++;,c++,C++,我正在尝试构建一个小型开源Web服务器,这段代码适用于大型文本文件,如.mp3s/.flac/binary(我尝试发送“cat”) std::ifstream文件; open(filepath.c_str(),std::ifstream::binary | std::ios::in); if(file.is_open()==true) { 结构统计; int rc=stat(filepath.c_str(),&stat_buf); long int a=统计数据大小; std::ostrings
std::ifstream文件;
open(filepath.c_str(),std::ifstream::binary | std::ios::in);
if(file.is_open()==true)
{
结构统计;
int rc=stat(filepath.c_str(),&stat_buf);
long int a=统计数据大小;
std::ostringstream tempLen;
tempLenstd::string(buffer).length()
对于二进制数据的缓冲区没有意义。string对象只会将数据复制到第一个零字节(因为它认为字符串是字符数据的空终止符)。因此,调用length
只会测量该部分数据
因此,您的缓冲区实际上已被gcount
所指示的数据量填充。您只需以非基于字符串的方式使用它。而且,除了第一个答案所说的,即使是文本文件,看起来您的程序行为也未定义。您正在分配一个1024字节的字符缓冲区,并且定格1023个字符
不能保证缓冲区中的最后一个字符是“\0”。因此,即使使用文本文件,偶尔也会使用new[]
操作符可能会回收一些以前使用过的内存,在1024个字符中还有其他内容,std::string
的构造函数将愉快地继续向前扫描,直到找到“\0”字符,将所有内容解释为您试图复制的文件的一部分
std::ifstream file;
file.open(filepath.c_str(), std::ifstream::binary | std::ios::in);
if(file.is_open() == true)
{
struct stat stat_buf;
int rc = stat(filepath.c_str(), &stat_buf);
long int a = stat_buf.st_size;
std::ostringstream tempLen;
tempLen << stat_buf.st_size;
setHeader("Content-Length", tempLen.str().c_str());
setHeader("Content-Type", getMimeType(filepath.c_str()));
long int chunkSize = 1024; // <1MB
do {
char *buffer = new char[chunkSize];
file.read(buffer, chunkSize - 1);
std::cout << "Chars in buffer: " std::string(buffer).length() << std::endl;
//send(buffer);
std::cout << "Chars read by ifstream: " << file.gcount() << "\n\n";
delete[] buffer;
} while(!file.eof());
file.close();
ACCESS [26/9/2014:0:14:44] Client requested using "GET" "/cat"
Chars in buffer: 7
Chars read by ifstream: 1023
Chars in buffer: 0
Chars read by ifstream: 1023
Chars in buffer: 1
Chars read by ifstream: 1023
Chars in buffer: 5
Chars read by ifstream: 1023
Chars in buffer: 12
Chars read by ifstream: 1023
Chars in buffer: 12
Chars read by ifstream: 1023