c++ - 无法使用 ifstream 将 txt 文件的最后一部分写入 cout

标签 c++ file-io ifstream cout eof

下面的代码将打印我正在使用的示例文本文件中的所有文本,除了它的最后一个小片段。我认为这与我使用的 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/

相关文章:

c++ - 调试 :FASTLINK - What is this error?

python - 什么是 Python 的良好临时存储和传输格式?

c - fgets() 是否总是以 null 终止它返回的字符串?

C++ - 简单的 ifstream 错误

c++ - 设置QFIle保存目录

c++ - 速度基于时间而不是 FPS

c++ - QTextEdit 的内存问题

c - 如何使用 C 编程读取 Visual Studio Code 中的输入文件?

c++ - 使用 ifstream 时出现无效空指针错误

c++ - 解析未知大小的字符串