C language > Beginner questions

Unexpected filepos after skipping a pascal string

(1/1)

jw:
Hello everybody,

suppose I have a pascal type string "RecLen" (binary 06 00 00 00  52 65  63  4C  65 6E) and I want to skip it. I read the prepended length and use it on fseek like so:

--- Code: ---fseek(stdin, readu32(), SEEK_CUR)
--- End code ---
which works in part of my code. But sometimes it only skips "RecLe" and subsequent reads return nonsense.

I checked fseek is always returning zero (i.e. success) and readu32 of course is called before fseek (I checked the disassembly). I experimented with fflush(stdin) and ftell(stdin), because it may be a buffering problem or some optimization with the file position indicator (though I switched it off for bug hunting). I do not see a mistake, but it may be obvious to you. Please give me a hint.

Thank you for your time and for considering the problem.

PS: Just in case...

--- Code: ---uint32_t readu32(void)
{
uint32_t ret;

if (fread(&ret, sizeof(uint32_t), 1, stdin) < 1) {
fputs("read error", stderr);
exit(-1);
}
return ret;
}
--- End code ---

TimoVJL:
fseek() isn't reliable with stdin, better to read a file instead.
sometimes piping is difficult to do.

Bitbeisser:

--- Quote from: TimoVJL on January 05, 2021, 05:22:43 PM ---fseek() isn't reliable with stdin, better to read a file instead.
sometimes piping is difficult to do.

--- End quote ---
Yeah, I don't think that fseek() behavior in case of stdin is
 properly defined, just like you can't get a file size of it. This is one of those cases where the *ix philosophy of "everything is a file" in C shows its idiocy...

Ralf

jw:
That is disappointing.

Before seeing your reply, I had double-checked with WCRT and thought to have found a bug in Pelles CRT. This would have been right off my first contribution.   :D

Oh well, I just want to skip forward a few byte, so I replaced fseek with loops of fgetc. Works for me(tm).

TimoVJL:
With setbuf or setvbuf a user buffer can be usable to some purboses.

Navigation

[0] Message Index

Go to full version