NO

Author Topic: Unexpected filepos after skipping a pascal string  (Read 1866 times)

Offline jw

  • Member
  • *
  • Posts: 2
Unexpected filepos after skipping a pascal string
« on: January 05, 2021, 04:36:28 PM »
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: [Select]
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...
Code: [Select]
uint32_t readu32(void)
{
uint32_t ret;

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

Offline TimoVJL

  • Global Moderator
  • Member
  • *****
  • Posts: 2091
Re: Unexpected filepos after skipping a pascal string
« Reply #1 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.
May the source be with you

Offline Bitbeisser

  • Global Moderator
  • Member
  • *****
  • Posts: 772
Re: Unexpected filepos after skipping a pascal string
« Reply #2 on: January 07, 2021, 08:21:02 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
« Last Edit: February 12, 2021, 05:09:43 PM by Bitbeisser »

Offline jw

  • Member
  • *
  • Posts: 2
Re: Unexpected filepos after skipping a pascal string
« Reply #3 on: January 11, 2021, 04:24:34 PM »
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).

Offline TimoVJL

  • Global Moderator
  • Member
  • *****
  • Posts: 2091
Re: Unexpected filepos after skipping a pascal string
« Reply #4 on: January 12, 2021, 09:18:36 AM »
With setbuf or setvbuf a user buffer can be usable to some purboses.
May the source be with you