Bug 29601 - fclose() doesn't flush the output as it should be
Summary: fclose() doesn't flush the output as it should be
Status: RESOLVED INVALID
Alias: None
Product: glibc
Classification: Unclassified
Component: stdio (show other bugs)
Version: 2.28
: P2 normal
Target Milestone: ---
Assignee: Not yet assigned to anyone
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2022-09-22 14:51 UTC by abdulrahman mahmoud
Modified: 2022-09-23 05:25 UTC (History)
2 users (show)

See Also:
Host:
Target:
Build:
Last reconfirmed:
fweimer: security-


Attachments

Note You need to log in before you can comment on or make changes to this bug.
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.