Search code examples
c++fileobject-files

Read integers from .obj file in c++


I have following problem. I need read integers from file xxx.obj. Integers are always 4B.

If i use hexdump -C to file, it looks:

04 00 00 00 06 00 00 00  08 00 00 00 50 00 00 00

One pair is 1B.

This is, how i open file:

ifstream fs1;
fs1.open( srcFile1, ios::in | ios::binary );

This is, how i read 1B from file in loop:

while( fs1.get( c ) )
  {
    cnt = (int)(unsigned char)c;
    cout << cnt << endl;

  }

Out is:

4
0
0
0
6
0
0
0
8
0
0
0
80
0
0
0

Any idea how to read directly int or how to read 4x 1B and then convert to int?


Solution

  • I'd suggest using the int32_t data type so you can be sure of getting a 4-byte int. Or use uint32-t if you want unsigned numbers.

    int32_t x; // Make sure integer is 4 bytes
    fs1.read(&x, sizeof(x)); // Read from file