Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reading bytes with ifstream

Tags:

c++

file-io

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

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. Something wrong about buffering? What did I do wrong?

EDIT:

I just found out something that might be the cause: in the file I use CRLF line endings (2 bytes), but all the above methods return only LF, so at the end of each line i is incresed only by one, however there are 2 bytes in the file. So my question is: how can I obtain both CR and LF separately?

like image 898
Dave Avatar asked Jun 22 '12 19:06

Dave


1 Answers

try

f.read(&b, 1);

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

like image 117
Beta Avatar answered Oct 02 '22 14:10

Beta