Can't write the last part of a txt file to cout using ifstream
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?
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());
}
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();
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.
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;
精彩评论