开发者

Reading binary files

开发者 https://www.devze.com 2023-02-27 16:44 出处:网络
I\'ve to read data from binary file. This binary data format is: 0x00 0x00 0x01 - is delimiter after this delimiter there is raw data byte array.

I've to read data from binary file. This binary data format is: 0x00 0x00 0x01 - is delimiter after this delimiter there is raw data byte array. So, to sum up, my binary file looks like:

0x00 0x00 0x01 (here is raw data byte) 0x00 0x00 0x01 (here is another block of raw data bytes) 0x00 0x00 0x01 ....

So i've wrote such code to parse my file (I'm not very familiar with C)

ifstream inp("myfile.bin",ios::binary);
char b1, b2, b3;
while (!inp.eof())
    {
        inp.read(&b1,sizeof(b1));
        inp.read(&b2,sizeof(b2));
        inp.read(&b3,sizeof(b3));
        //finding first delimiter (data starts from delimiter)
        while (!((0==b1)&&(0==b2)&&(1==b3)))
        {
            b1=b2;
            b2=b3;
            if (inp.eof())
                break;      
            inp.read(&b3,sizeof(b3));
        }
        if (inp.eof())
            break;              
        char* raw=new char[65535];
        int rawSize=0;

        inp.read(&b1,sizeof(b1));
        inp.read(&b2,sizeof(b2));
        inp.read(&b3,sizeof(b3));

        raw[rawSize++]=b1;
        raw[rawSize++]=b2;
        if (inp.eof())
            break;开发者_JAVA百科  

        //reading raw data until delimiter is found
        while (!((0==b1)&&(0==b2)&&(1==b3)))
        {
            raw[rawSize++]=b3;
            b1=b2;
            b2=b3;
            if (inp.eof())
                break;      
            inp.read(&b3,sizeof(b3));
        }
        rawSize-=2; //because of two bytes of delimiter (0x00 0x00) would be added to raw

        //Do something with raw data

        if (inp.eof())
            break;

        inp.putback(1);
        inp.putback(0);
        inp.putback(0);

        delete []raw;
    }

But sometimes this code falls into infinite loop. Could you advice me something? Thanks


I think the problem there is that putback fails. As far as i recall, putback is guaranteed to work only once; second invocation will fail if the internal read buffer is aligned (that is, very rarely; seems like your situation).

To fix, get rid of putback. First of all, move the loop commented as "finding first delimiter" out of the outer while loop: the comment suggests that this code should only run once. After you do it, pay attention that at the beginning of the outer while loop, the sequence 0x00 0x00 0x01 has just been found, so the code doesn't have to use putback and look for it again.


  • You're using feof() wrong, it's only valid after a read has been attempted and failed.

  • How do you know that your magic byte sequence 0 0 1 doesn't appear inside the data? If the data is just a "binary array" that doesn't sound like it provides much of a guarantee ...

0

精彩评论

暂无评论...
验证码 换一张
取 消