
reading from binary files
Quote:
> I have written some code to read binary data from a file and convert
> it into the appropriate data type for use in my program. I have
> written routines that get shorts, longs, floats and doubles. It
> seemed silly to write a routine for getting chars, since "getc"
> works fine.
> Here's the problem. When I call "getc" it updates some pointer
> somewhere to point to the next char in the stream. My routines do not
> have access to this pointer, so I have to tell them where to start
> reading the data. This works, but it's really annoying to have to
> track the position in the stream which I read sequentially, straight
> through, one time. Is there a way to access the pointer that "getc"
> uses, or maybe a library function that I could substitute for my own?
> Here's one of the functions that returns data of a specific type to
> the calling program:
> float getfloat(FILE *fileptr, long offset, int orgin) {
> float floatdata;
> void *ptr;
> int status;
> fseek(fileptr, offset, orgin);
> ptr =&floatdata;
> status = fread(ptr, 4, 1, fileptr);
> /* read one object of four bytes */
> return floatdata;
Unless I misunderstand your problem, it looks like you're trying
too hard! You don't need to keep track of your position in the
file or do any fseek()s. When you do a getc(), the Standard I/O
internal pointer is updated to point to the character after the
one you read. If you then do an fread(ptr, 4, 1, fileptr), it
will read the next four characters, and again update the pointer
to point to the character after the last one it read. Using the
various stdio routines to read from the file will simply step
through it sequentially. If you want to skip over a part of the
file, just use fseek(fileptr, skip_count, SEEK_CUR) to skip the
skip_count characters after the last one you read.
Am I missing something?
[ Posted and emailed since the question was a little while ago
and Andy may no longer be watching for replies. ]
Sent via Deja.com http://www.deja.com/
Share what you know. Learn what you don't.
--