fwrite on a closed file

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

fwrite on a closed file

Sripathi Kodi
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.
Reply | Threaded
Open this post in threaded view
|

Re: fwrite on a closed file

Roland McGrath
> When fwrite is called on a closed file, it is supposed to return zero as
> the number of bytes written.

I don't know where you got this idea.  After you call fclose, any other use
of that FILE * is undefined behavior.
Reply | Threaded
Open this post in threaded view
|

Re: fwrite on a closed file

Sripathi Kodi
Roland McGrath wrote:
>>When fwrite is called on a closed file, it is supposed to return zero as
>>the number of bytes written.
>
>
> I don't know where you got this idea.  After you call fclose, any other use
> of that FILE * is undefined behavior.

Roland,

I had only concentrated on what specs say about fwrite, so I had missed this
part about fclose. Sorry about that and thanks for pointing it out.

Sripathi.