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

半世苍凉 提交于 2019-12-25 02:31:30

问题


The code below will print all of the text from the sample text file I'm using except for the last little snippet of it. I think this has something to do with the eof or the byte size I'm using not working as I expect.

#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;
}

What am I missing?


回答1:


As you already know, you have a wrong size of buffer. The other thing is the read of less than 1024 characters (going to happen at the end if your file doesn't have exactly n*1024 bytes). Take the advantage of istream::gcount which gives you number of characters extracted by last read:

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



回答2:


1) You are not correctly calcuulating the size of the final buffer.

2) You are not correctly recognizing all of the possible error conditions.

Try:

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


PS. If you are really trying to copy the named file to standard out, there is a much easier way:
ifstream stream("SampleFile.txt", ios::binary);
std::cout << stream.rdbuf();



回答3:


Looks like the problem is that your last read doesn't happen to be exactly the size of your buffer. You need to handle that as a special case. For details, see http://www.cplusplus.com/reference/iostream/istream/read/.

Oh, and it looks like your buffer is 8 bytes long but you read 1024 bytes. That's bad.




回答4:


Since you know the size of the file, why not read the entire file at once?

buffer = new char[length];

stream.read( buffer, length );
cout.write( buffer, length );

delete[] buffer;


来源:https://stackoverflow.com/questions/6740425/cant-write-the-last-part-of-a-txt-file-to-cout-using-ifstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!