Reading a file and then writing something back
Jeff Epler
jepler at unpythonic.net
Wed Jul 21 11:30:06 EDT 2004
Python's file object is based on ISO C's file I/O primitives
(fopen, fread, etc) and inherits both the requirements of the standard
and any quirks of your OS's C implementation.
According to this document
http://www.lysator.liu.se/c/rat/d9.html#4-9-5-3
a direction change is only permitted after a "flushing" operation
(fsetpos, fseek, rewind, fflush). file.flush calls C's fflush.
I believe that this C program is equivalent to your Python program:
#include <stdio.h>
int main(void) {
char line[21];
FILE *f = fopen("testfile", "w");
fputs("kevin\n", f);
fputs("dan\n", f);
fputs("pat\n", f);
fclose(f);
f = fopen("testfile", "r+");
fgets(line, 20, f); printf("%s", line);
fgets(line, 20, f); printf("%s", line);
fflush(f);
if(fputs("chris\n", f) == EOF) { perror("fputs"); }
fclose(f);
return 0;
}
On my Linux machine, it prints
kevin
pat
and testfile's third and final line is "chris".
On a windows machine nearby (compiled with mingw, but using msvcrt.dll)
it prints
kevin
dan
fputs: No error
and testfile's third and final line is "pat".
If I add fseek(f, 0, SEEK_CUR) after fflush(f), I don't get a failure
but I do get the curious contents
kevin
dan
pat
chris
If I use just fseek(f, 0, SEEK_CUR) I get no error and correct
contents in testfile.
I don't have a copy of the actual C standard, but even Microsoft's
documentation says
When the "r+", "w+", or "a+" access type is specified, both reading
and writing are allowed (the file is said to be open for “update”).
However, when you switch between reading and writing, there must be
an intervening fflush, fsetpos, fseek, or rewind operation. The
current position can be specified for the fsetpos or fseek
operation, if desired.
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vccore98/HTML/_crt_fopen.2c_._wfopen.asp
so it smells like a bug to me. Do you happen to be using Windows? I
guess you didn't actually say.
Jeff
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20040721/abc24b6f/attachment.sig>
More information about the Python-list
mailing list