Reputation: 162
In the following example,
ifstream myFile;
myFile.open("example.txt", ios::binary);
cout << myFile.rdbuf() << endl;
myFile.close();
The contents of the file will be printed, in its entirety on one line. You can also do it like this:
ifstream myFile;
myFile.open("example.txt", ios::binary);
unsigned char character = myFile.get();
while(myFile){
cout << "one character = ";
cout << character;
character = myFile.get(); //gets each individual character, 1 at a time
}
myFile.close();
And it will print the contents of the file, one character at a time. However, if you try to do the methods one after the other (in any order), only one method will actually print anything. Could someone explain why, in the following example, the call to rdbuf()
won't print the contents of the file?
ifstream myFile;
myFile.open("example.txt", ios::binary);
unsigned char character = myFile.get();
while(myFile){
cout << "one character = ";
cout << character;
character = myFile.get(); //gets each individual character, 1 at a time
}
cout << myFile.rdbuf() << endl;
myFile.close();
Thank you!
Upvotes: 0
Views: 1404
Reputation: 19042
As you read in from a stream, the read position is incremented. After reading in an entire file character by character, the read position is at the end of file. In this case, rdbuf()
(the read buffer) has nothing further of interest.
If you wanted to print the file again using rdbuf()
you can set the read position with myFile.seekg(0, std::ios::beg);
prior to attempting to print. In this specific example an error bit may already be set, so you may need to do a myFile.clear()
before moving the read pointer.
Upvotes: 1