Schrami
Schrami

Reputation: 89

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?

Upvotes: 0

Views: 155

Answers (2)

Ionel POP
Ionel POP

Reputation: 833

You could try

int val;
while(fs)
{
     fs.read(&val, sizeof(val);
     if(fs) cout<<val<<endl
}

The function read of a stream allows to read an arbitrary chunk of data at once and copy it into a zone of memory.

The code above read chunks of size of int at once and copy them into the memory zone of an int - val.

Upvotes: 0

Logicrat
Logicrat

Reputation: 4468

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

Upvotes: 1

Related Questions