Unexpected filepos after skipping a pascal string

Started by jw, January 05, 2021, 04:36:28 PM

Previous topic - Next topic

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:
fseek(stdin, readu32(), SEEK_CUR)
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...
uint32_t readu32(void)
{
uint32_t ret;

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


TimoVJL

fseek() isn't reliable with stdin, better to read a file instead.
sometimes piping is difficult to do.
May the source be with you

Bitbeisser

#2
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.
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.
May the source be with you