This is the mail archive of the libc-alpha@sourceware.org mailing list for the glibc project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

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.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]