Dave
Dave

Reputation: 690

reading bytes with ifstream

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?

Upvotes: 8

Views: 31982

Answers (2)

Dave
Dave

Reputation: 690

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

Seems like the CR character messes up both ifstream and cout, that caused my confusion, I will keep this in mind.

Upvotes: 0

Beta
Beta

Reputation: 99094

try

f.read(&b, 1);

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

Upvotes: 24

Related Questions