This is the mail archive of the
libc-alpha@sourceware.org
mailing list for the glibc project.
fwrite on a closed file
- From: Sripathi Kodi <sripathik at in dot ibm dot com>
- To: libc-alpha at sourceware dot org
- Date: Fri, 24 Feb 2006 16:59:05 +0530 (IST)
- Subject: fwrite on a closed file
Hi,
When fwrite is called on a closed file, it is supposed to return zero as the
number of bytes written. However, glibc does not recognize that the file is
closed. It seems to copy the data to it's buffer and return the number of
bytes written to the application. Error is reported only when number of bytes
to be written is large and hence data is needed to be flushed from glibc
buffers. A simple testcase attached below can demonstrate this problem. fwrite
succeeds and only fflush returns an error.
Do we need to add a check for closed file while writing data to it? If yes,
should the check be in _IO_new_file_xsputn()? Should the check be something
like:
if (!_IO_file_is_open(f)) {
f->_flags |= _IO_EOF_SEEN;
return 0;
}
Testcase:
---------
#include <stdio.h>
#include <errno.h>
main()
{
FILE *fp ;
char buffer[] = "abcdef";
short el_size;
el_size = sizeof(char);
int ret;
extern int errno;
if(!(fp = fopen("abc", "w+b")))
return 1;
fclose(fp);
if ((ret = fwrite((char *)buffer, el_size,6, fp)) != 6)
printf("fwrite Failed!. errno = %d\n", errno);
else
printf("fwrite Success!\n");
if ((ret = fflush(fp)) != 0)
printf("fflush failed. errno = %d\n", errno);
}
Thanks and regards,
Sripathi.