From: "Ben Davis" Newsgroups: comp.os.msdos.djgpp Subject: Re: Reading in Data Date: Sat, 22 Apr 2000 02:27:15 +0100 Organization: Customer of Planet Online Lines: 50 Message-ID: <8dqv8b$3b8$1@newsg4.svr.pol.co.uk> References: NNTP-Posting-Host: modem-100.altace.dialup.pol.co.uk X-Trace: newsg4.svr.pol.co.uk 956366923 3432 62.136.76.228 (22 Apr 2000 01:28:43 GMT) NNTP-Posting-Date: 22 Apr 2000 01:28:43 GMT X-Complaints-To: abuse AT theplanet DOT net X-Newsreader: Microsoft Outlook Express 4.72.3110.5 X-MimeOLE: Produced By Microsoft MimeOLE V4.72.3110.3 To: djgpp AT delorie DOT com DJ-Gateway: from newsgroup comp.os.msdos.djgpp Reply-To: djgpp AT delorie DOT com 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