Bug 29601

Summary: fclose() doesn't flush the output as it should be
Product: glibc Reporter: abdulrahman mahmoud <abdulrahman.mahmoud75>
Component: stdioAssignee: Not yet assigned to anyone <unassigned>
Status: RESOLVED INVALID    
Severity: normal CC: drepper.fsp, fweimer
Priority: P2 Flags: fweimer: security-
Version: 2.28   
Target Milestone: ---   
See Also: https://sourceware.org/bugzilla/show_bug.cgi?id=1190
Host: Target:
Build: Last reconfirmed:

Description abdulrahman mahmoud 2022-09-22 14:51:31 UTC
I have created a mini example to test the fgets() utility but when i run this example i don't see any output in the shell, below is my example:

#include <stdio.h>

int main () {
   FILE *fp, *fd_3, *fd_2;
   char str[60];
   char str1[] = "writing to file ";
   char str2[] = "my file";

   fp = fopen("file/test_fopen" , "w");
   fclose(fp);
   fd_3 = fopen("file/test_fopen" , "r");
   fp = fopen("file/test_fopen" , "a");
   fwrite(str1 , 1 , sizeof(str1) , fp);
   if( fgets (str, 60, fd_3)!=NULL ) {
      puts(str);
   }
   fclose(fp);
   fd_2 = fopen("file/test_fopen" , "a");
   fwrite(str2 , 1 , sizeof(str2) , fd_2);
   if( fgets (str, 60, fd_3)!=NULL ) {
      puts(str);
   }
   fclose(fd_2);
  
   return(0);
}

When i compile and run this code against glibc-2.17 i receive an output "writing to file" on the shell but when i compile against glibc-2.28, there is no output.

So is this an expected behavior? is the way of flushing when calling fclose() changed between the two versions?
Comment 1 Andreas Schwab 2022-09-22 16:05:15 UTC
This is because EOF is now sticky, see commit 2cc7bad0ae.  You need to call fseek or clearerr before you can read more from a changing file.
Comment 2 abdulrahman mahmoud 2022-09-22 18:01:49 UTC
(In reply to Andreas Schwab from comment #1)
> This is because EOF is now sticky, see commit 2cc7bad0ae.  You need to call
> fseek or clearerr before you can read more from a changing file.

Thanks Andreas, i have called clearerr and it solved the issue.
Comment 3 Florian Weimer 2022-09-23 05:25:26 UTC
Closing per comment 1 and comment 2.