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

Can't write the last part of a txt file to cout using ifstream

本文关键字:最后 一部分 cout 文件 txt ifstream      更新时间:2023-10-16

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

1)您没有正确计算最终缓冲区的大小。

2)您没有正确识别所有可能的错误情况。

试题:

while(stream) {
    stream.read(buffer, 1024);
    cout.write(buffer, stream.gcount());
}


p 。如果您真的想将命名文件复制到标准输出,有一个更简单的方法:

ifstream stream("SampleFile.txt", ios::binary);
std::cout << stream.rdbuf();

看起来问题是,您的最后一次读取并不恰好是您的缓冲区的大小。你得把它当作特例来处理。详细信息请参见http://www.cplusplus.com/reference/iostream/istream/read/

哦,看起来你的缓冲区是8字节长,但你读了1024字节。这是不好的。

既然知道文件的大小,为什么不立即读取整个文件呢?

<>之前Buffer = new char[length];流。读取(buffer, length);cout。Write (buffer, length);删除[]缓冲区;