Skip to main content
gamedev.net
🔒 Locked

c++: reading binary file

Started by Alessandro 1 reply 700+ views
Original Post
Alessandro
Alessandro
Hi, i'm trying to read a binary file with the following structure: [byte offset] [length] [content] [0] [10] [10 char string] [10] [4int] [columns] In practice i have to read 10 chars and then an int, as you can see. I did the following:

FILE *bt;
bt=fopen("bh.bt", "rb"); //open the file in binary mode
char header[11]={0};
int columns;
fscanf(bt, "%10c", header);
fscanf(bt, "%i", &columns);

The initial 10 chars are correctly read (they contain the file title), while the columns var get an odd value (-8865340), while it should be 4520. I'm sure i did something wrong, perhaps it's so simple i can't see it...
RobTheBloke
RobTheBloke
you can't use fscanf to read binary files, and you can't use fprintf to write binary files. You should be using fread & fwrite.

FILE *bt;bt=fopen("bh.bt", "rb"); //open the file in binary modechar header[11]={0};int columns;fread(header,1,10,bt);fread(&columns,sizeof(int),1,bt);

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.