0

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?

Schrami
  • 89
  • 1
  • 12

2 Answers2

1

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
Logicrat
  • 4,438
  • 16
  • 22
0

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.

Ionel POP
  • 743
  • 7
  • 12
  • While this code may answer the question, providing additional context regarding *why* and/or *how* this code answers the question improves its long-term value. – Benjamin W. Mar 26 '16 at 07:11