NetBSD-Bugs archive

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index][Old Index]

Re: kern/59197 (file descriptor seek -> read -> write causes file pos inconsistency)



Synopsis: file descriptor seek -> read -> write causes file pos inconsistency

State-Changed-From-To: open->feedback
State-Changed-By: riastradh%NetBSD.org@localhost
State-Changed-When: Wed, 19 Mar 2025 13:38:25 +0000
State-Changed-Why:
Lua implements f:read/write in terms of stdio.h fread/fwrite.  Files
opened for reading and writing are subject to the following
restrictions from standard C (C99, Sec. 7.19.5.3 `The fopen function',
clause 6, p. 272):

> [...] However, output shall not be directly followed by input without
> an intervening call to the fflush function or to a file positioning
> function (fseek, fsetpos, or rewind), and input shall not be directly
> followed by output without an intervening call to a file positioning
> function, unless the input operation encounters end-of-file.

We have the following admonition in the fread(3) and fwrite(3) man
pages:

> Mixing fread() and fwrite() calls without setting the file position
> explicitly using fsetpos(3) between read and write or write and read
> operations will lead to unexpected results because of buffering the
> file pointer not being set to the expected position after each
> operation completes.  This behavior is allowed by ANSI C for
> efficiency and it will not be changed.

(This should maybe clarify that fseek(3) and fseeko(3) work too -- any
of the file positioning functions.)

Try calling f:seek('cur', 0) between the last read and the next write
after it:

@@ -24,6 +24,7 @@
        assert('22' == f:read(2))
        assert('33' == f:read(2))
 fs(0); assert('11' == f:read(2))
+f:seek('cur', 0)
 fw'20';
 local p = f:seek'cur'
 print('pos', p); assert(4 == p)

Does that help?





Home | Main Index | Thread Index | Old Index