Mail Archives: djgpp/2000/04/21/21:12:58
Ben Alford wrote in message ...
>Hi
>
>I am trying to read data from a file. The file is in binary format. The
data
>is either 1,2 or 4 bytes.
>I need to convert the byte information into an integer value.
>The technique that I have tried for reading a field of 2 bytes would be,
>
>char twobyte[3]
>
> fread(twobytes, sizeof(twobytes), 1, FILE)
>strcpy(twobytes, twobytes, 2)
> twobyte[2] = '\0'
> num = (int)(unsigned char)twobyte[1]*256 + (int)(unsigned char)twobyte[0]
>
>This sort of works but feels nasty. It doesn't work for values that are
>negative.
It looks a bit nasty as well. strcpy() takes 2 arguments, not 3 - do you
mean strncpy()? And you've used two different symbols here, 'twobyte' and
'twobytes'. Also, If they are meant to be the same, it seems you're reading
3 bytes from the file - which would mess up the next value you try to read.
I'm surprised you're having this trouble. For me, this works every time:
fread(&num, sizeof(num), 1, FILE);
num can be declared as (un)signed char, (un)signed short, (un)signed int, or
whatever. Even a struct if you want. If you want to read a string though,
use a different function. You can also use fwrite() with the same parameters
to save the file.
This works because the format for storing numbers in a file is the same as
the format for storing numbers in memory - at least in most cases. It should
work here.
You can also use the following:
int getc(FILE *file) - read one unsigned character from file.
int getw(FILE *file) - read a word from file (I'm not sure whether this will
work - it depends on the byte ordering the function assumes).
I'm not sure what the equivalent for 32-bit integers is, but I'm sure
someone will tell you soon... In the meantime, use fread().
Hope this helps.
Ben Davis
- Raw text -