fseek/fgetc puzzle

Nathan Wagner nw at hydaspes.if.org
Mon Feb 20 21:55:56 AEDT 2023


On Mon, Feb 20, 2023 at 09:44:41PM +1100, Darren Tucker wrote:
> $ cat test.c
> #include <stdlib.h>
> #include <stdio.h>
> int main(void)
> {
>         FILE *f = fopen("testfile", "w");
>         printf("fputc A=%d\n", fputc('A', f));

Is fputc() here somehow being evaluated twice?  What happens
if you move the fputc() call outside the printf() call?
Or create it separately than this program.

>         fclose(f);
> 
>         f = fopen("testfile", "a+b");
>         printf("fseek=%d\n", fseek(f, -1L, SEEK_END));
>         printf("c=%d\n", fgetc(f));
>         printf("fputc B = %d\n", fputc('B', f));

My suggestion of course fails to explain why there's only one 'B'.
I would create the initial file separately from the test program.

I don't recall, but is there a guaranteed fflush() on open file
descriptors at program exit?  Does an explicit call to fflush() do
anything?

> $ gcc test.c && ./a.out && od -x -c testfile
> fputc A=65
> fseek=0
> c=65
> fputc B = 66
> 0000000    4141    0042
>            A   A   B
> 0000003

FWIW, this is the same output I get on both a linux and macos box.

-- 
nw


More information about the openssh-unix-dev mailing list