Reading bytes with ifstream

I am relatively new to C ++ and have some problems with ifstream. All I want to do is read the byte file by byte, however reading always fails in the middle of the file. My code is:

void read(ifstream&f) { unsigned char b; for (int i=0;;++i) { if(!f.good()) { cout<<endl<<"error at: "<<i; return; } f>>b; // b=f.get(); and f.read(&b, 1); doesnt work either cout<<b; /* ... */ } } 

It reads the first few hundred bytes correctly, then the rest of the file is skipped. Is there something wrong with buffering? What have I done wrong?

EDIT:

I just found out what could be the reason: in the file I use CRLF line ends (2 bytes), but all of the above methods return only LF, so at the end of each line I incresed only one, but there are 2 bytes in the file. So my question is: how can I get both CR and LF separately?

+4
source share
2 answers

I finally started working by opening the file in binary mode (thanks to Alex for drawing my attention to it).

It looks like the CR symbol will ruin both ifstream and cout streams, which caused my confusion, I will keep that in mind.

+1
source

try

 f.read(&b, 1); 

Both << and get() are for text, not binary data.

+9
source

All Articles