Reading numbers from file in C
I am primarily a Python programmer, but I've been working with C because Python is too slow for graphics (20 fps moving fractals FTW). I'm hitting a sticking point though... I wrote a little file in a hex editor to test with. When I try reading the first byte, 5A, it correctly gives me 90 with a program like this...
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
FILE *data;
int main(int argc, char* argv[])
{
data=fopen("C:\\vb\\svotest1.vipc","r+b");
unsigned char number;
fread(&number,1,1,data);
printf("%d\n",number);
}
But when I try reading the first four bytes, 5A F3 5B 20, into an integer I get 542896986
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
FILE *data;
int main(int argc, char* argv[])
{
data=fopen("C:\\vb\\svotest1.vipc","r+b");
unsigned long number;
fread(&number,1,4,data);
printf("%d\n",number);
}
It should be 1525898016!!! The problem is it has reversed the byte order. GAH! Of course! The way this program works will depend on the machine. And now that we are on the subject, even the byte won't work on every machine!
So I need help... In Python I can use struct.pack and struct.unpack to pack data into bytes using any format (long, short, single, double, signed, unsigned, big endian, little endian) and unpack it. I need something like this in C... I could write it myself开发者_开发技巧 but I don't know how.
The easiest way to handle this portably is probably to use htonl
on the data before you write it to the file (so the file will be in network/big endian order) and ntohl
when you read (converts the network order data to the local convention, whatever that is).
If you have to do much more than a few values of one type, you may want to look into a more complete library for the purpose, such as Sun XDR or Google Protocol Buffers.
I think you can figure out the (Endianness) http://en.wikipedia.org/wiki/Endianness and then read the byte order.
Like this?
unsigned long bin = 0;
unsigned char temp = 0;
for(unsigned char i = 0; i < 4; i++) {
fread(&temp,1,1,data);
bin = (bin << 8) | temp;
}
This results in the first part being the most significant. I think that's what you want.
精彩评论