c++ - Why does rdbuf() not print anything? -


in following example,

ifstream myfile; myfile.open("example.txt", ios::binary); cout << myfile.rdbuf() << endl;  myfile.close(); 

the contents of file printed, in entirety on 1 line. can 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 @ time } myfile.close(); 

and print contents of file, 1 character @ time. however, if try methods 1 after other (in order), 1 method print anything. explain why, in following example, call rdbuf() won't print contents of 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 @ time } cout << myfile.rdbuf() << endl;  myfile.close();      

thank you!

as read in stream, read position incremented. after reading in entire file character character, read position @ end of file. in case, rdbuf() (the read buffer) has nothing further of interest.

if wanted print file again using rdbuf() can set read position myfile.seekg(0, std::ios::beg); prior attempting print. in specific example error bit may set, may need myfile.clear() before moving read pointer.


Comments

Popular posts from this blog

c++ - Delete matches in OpenCV (Keypoints and descriptors) -

java - Could not locate OpenAL library -

sorting - opencl Bitonic sort with 64 bits keys -