-
Reading Binary files
Hey,
I've looked over the binary I/O post and read over some tutorials on line, but I still can't make the program read in a binary number properly.
I've tried:
Code:
char num[5];
int DataFormat;
inp>>DataFormat;
// and
inp.read(num, sizeof(long));
num[5] = '\0';
DataFormat = atoi(num);
It doesn't interprit DataFormat properly in either case. The input file is binary. to place the poiter at the correct position I use:
Code:
ifstream inp;
inp.open("test.baf", ios_base::binary);
inp.seekg(549,ios::beg);
is there another way to read in 4 bytes into a longint variable fro ma binary file?
-
Try
Code:
long x;
inp.read(&x, sizeof(long);
You might need to cast &x to char*.
-
Nope, doesn't work either.
Thanks though.
-
Check out this line:
num[5] = '\0';
Post an example of the bytes that is read from the file and the incorrect value assigned to DataFormat.
Kuphryn
-
Code:
DataFormat -858993460
&DataFormat 0x0012f5bc
thant's using : inp.read((char*)&DataFormat, sizeof(long));
If I use
Code:
inp.read(num, sizeof(long));
num[5] = '\0';
DataFormat = atoi(num);
I get
Code:
DataFormat -858993460
- num 0x0012f5c0 "ÌÌÌÌÌ"
[0] -52 'Ì'
[1] -52 'Ì'
[2] -52 'Ì'
[3] -52 'Ì'
[4] -52 'Ì'
num[5] 0 ''
-
Code:
inp.read((char*)&DataFormat, sizeof(long));
is correct (assuming a 4 byte int). Or better is:
Code:
inp.read((char*)&DataFormat, sizeof(DataFormat));
What's actually in your file at locations 549-552?
-
this is advance but i remember that you have to treat the file as binary while opening it
Code:
ofstream file ( "file.file", ios::binary );
-
>What's actually in your file at locations 549-552?
It should be 0,1 or 2 as a long int.
>you have to treat the file as binary while opening it
I do use ios::binary
-
god im stupid lol didnt read all of it hahaha sry
-
I would verify the data with this then (first seek to appropriate location):
Code:
char ch;
inp.read((char*)&ch, sizeof(ch));
cout << (int) ch << " ";
inp.read((char*)&ch, sizeof(ch));
cout << (int) ch << " ";
inp.read((char*)&ch, sizeof(ch));
cout << (int) ch << " ";
inp.read((char*)&ch, sizeof(ch));
cout << (int) ch << " ";
cout << endl;
It's possible the bytes are reversed (endian problem), but first see if the data looks right.
-
I've tried everything above. It doesn't come back properly. let me look into the file structure a bit more. Maybe I'm forgetting something there. Maybe later I'll be back with a new problem.
Thanks for all the help,
AS.