Reading numbers from file in C -
i python programmer, i've been working c because python slow graphics (20 fps moving fractals ftw). i'm hitting sticking point though... wrote little file in hex editor test with. when try reading first byte, 5a, correctly gives me 90 program 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 try reading first 4 bytes, 5a f3 5b 20, integer 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 1525898016!!! problem has reversed byte order. gah! of course! way program works depend on machine. , on subject, byte won't work on every machine!
so need help... in python can use struct.pack , struct.unpack pack data bytes using format (long, short, single, double, signed, unsigned, big endian, little endian) , unpack it. need in c... write myself don't know how.
the easiest way handle portably use htonl
on data before write file (so file in network/big endian order) , ntohl
when read (converts network order data local convention, whatever is).
if have more few values of 1 type, may want more complete library purpose, such sun xdr or google protocol buffers.
Comments
Post a Comment