下面的代码将打印我正在使用的示例文本文件中的所有文本,除了它的最后一个小片段。我认为这与我使用的 eof 或字节大小不符合我的预期有关。
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char* argv[]){
int length;
char* buffer;
//get file stream and open local file.
ifstream stream;
stream.open("SampleFile.txt", ios::binary);
stream.seekg(0, ios::end);
length = stream.tellg();
stream.seekg(0, ios::beg);
//read stream 1024 bytes at a time until all bytes of file are used
buffer = new char[1024];
bool eof = false;
while(!eof)
{
stream.read(buffer, 1024);
cout.write(buffer, 1024);
if(stream.eof())
eof = true;
//cout << i << endl;
//cout.write(buffer, 1024);
}
stream.close();
delete[] buffer;
return 0;
}
我错过了什么?
最佳答案
如您所知,您的缓冲区大小错误。另一件事是读取少于 1024 个字符(如果您的文件不完全是 n*1024
字节,将在最后发生)。利用 istream::gcount
为您提供上次读取提取的字符数:
char buffer[1024];
while(stream)
{
stream.read(buffer, 1024);
cout.write(buffer, stream.gcount());
}
关于c++ - 无法使用 ifstream 将 txt 文件的最后一部分写入 cout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6740425/