0

I have a file of type: data, and I want to read that file the same way I see the contents of the file with the command

od -D filename on Linux

In other words, the contents of the file are:

0000000 000002 000000 000002 000000 000002 000000 000002 000000
0000020 000004 000000 000004 000000 000004 000000 000004 000000
0000040 000006 000000 000006 000000 000006 000000 000006 000000
0000060

But with the od -D filename command on Linux, I see:

0000000 2 2 2 2
0000020 4 4 4 4
0000040 6 6 6 6
0000060

I want to read this file in C ++ so that I don't have to manipulate the data, but simply retrieve 222244446666

In the code below I am reading in a way that works, but if the file contains values ​​= 0, I will not be able to rescue them in the reading.

ifstream file2 (file, ios :: in);
        char ch;
        if (file2.is_open ())
        {
            while (! file2.eof ())
            {
                file2.get (ch);
                double num = ch;
                //if (num != 0) {
                    cout << num << endl;
                //}
            }
        }
        file2.close ();

When I read this way it looks like:

2
0
0
0
2
0
0
0
2
0
0
0
2
0
0
0
4
0
0
0
4
0
0
0
4
0
0
0
4
0
0
0
6
0
0
0
6
0
0
0
6
0
0
0
6
0
0
0
0

I want to know how I can read this file so that it only takes the real values, that is, 222244446666, but if it contains 0 values I also need to get them. Example: 000022224444 (That is why I commented if num != 0, this doesn't work for all cases)

That is, I need to eliminate these zeros as the od -D filename command does

1 Answers1

0

The data looks like 32 bit binary integers in little endian (PC) format. The octal dump is a bit misleading because you instruct it with -D to read 16 bit values. A 16 bit int with the value 2 is the byte sequence 0x2 0x0, but as an octal integer it is 2 (or, if we print leading 0s, 000002).

If you read it byte by byte your would see that.

The solution to your problem is to simply fread 32 bit ints, provided you are on in Intel compatible platform.

Peter - Reinstate Monica
  • 12,309
  • 2
  • 29
  • 52