kern/127335: [libc] fwrite(3) fails to generate error when applied to a read-only file

sean seburke at rent.com
Sat Sep 27 02:30:09 UTC 2008


The following reply was made to PR kern/127335; it has been noted by GNATS.

From: sean <seburke at rent.com>
To: bug-followup at FreeBSD.org, rfg at tristatelogic.com
Cc:  
Subject: Re: kern/127335: [libc] fwrite(3) fails to generate error when
	applied to a read-only file
Date: Fri, 26 Sep 2008 18:57:33 -0700

 fwrite does set errno correctly. I modified the demo code
 to call perror before and after, like so:
 
 #include <stdio.h>
 
 int
 main (void)
 {
     perror ("pre-fwrite");
     fwrite ("Hello world!", 1, 12, stdin);
     perror ("post-fwrite");
 
     if (ferror (stdin))
         printf ("Error writing to stdin\n");
     else if (feof (stdin))
         printf ("EOF detected while writing to stdin\n");
     else
         printf ("This shouldn't happen!\n");
 
     return 0;
 }
 
 Which produces this output:
 
 pre-fwrite: Unknown error: 0
 post-fwrite: Bad file descriptor
 This shouldn't happen!
 
 The relevant code is in wsetup.c, where is tests where the
 'WRite' or 'Read-Write' flags are set, and fails if not:
 
         if ((fp->_flags & __SWR) == 0) {
                 if ((fp->_flags & __SRW) == 0) {
                         errno = EBADF;
                         return (EOF);
                 }
 
 I believe that the fix is to set the error flag on failure,
 like so:
 
          if ((fp->_flags & __SWR) == 0) {
                 if ((fp->_flags & __SRW) == 0) {
                         fp->_flags |= __SERR;
                         errno = EBADF;
                         return (EOF);
                 }
  
 
 


More information about the freebsd-bugs mailing list