简体   繁体   中英

not getting expected output from fgets() after fflush()

Here is the simple code after fflush() we are not getting the expected output. We expect "Hello World file2" but it is showing some random garbage value as mentioned below.

FILE 2 b4  = output_reg : P\ufffd\ufffdr\ufffd
FILE 2 af  = output_reg : P\ufffd\ufffdr\ufffd
#include <stdio.h>

int main(void) {

  char output_reg[300], errstr[300];
  FILE *fd1, *fd2, *fd3, *fd4; 
  char *retno, *retseek;
  int len;

      fd4 = fopen("out2.log","w");
      fd3 = fopen("out2.log","r");

      fputs("Hello World file2!\n", fd4);


      fgets(output_reg, 30, fd3);
      printf("FILE 2 b4  = output_reg : %s\n",output_reg);
  
      fflush(fd4);

      fgets(output_reg, 30, fd3);
      printf("FILE 2 af  = output_reg : %s\n",output_reg);

}

After fputs("Hello World file2!\\n", fd4); nothing has been written to the file but only into an internal buffer. Therefore the out2.log file is still empty.

fgets(output_reg, 30, fd3) then tries to read from an empty file which fails but you don't check that. Then you print the content of output_reg anyway, hence the garbage.

Then you call fflush(fd4) which does actually write into the file, therefore the second fgets works fine.

Change your code to this and see what happens.

#include <stdio.h>
#include <stdlib.h>

int main(void) {

  char output_reg[300] = "mygarbage", errstr[300];
  FILE* fd1, * fd2, * fd3, * fd4;
  char* retno, * retseek;
  int len;

  fd4 = fopen("out2.log", "w");
  if (fd4 == NULL)
  {
    printf("fopen(\"out2.log\", \"w\") failed.");
    exit(1);
  }

  fd3 = fopen("out2.log", "r");
  if (fd3 == NULL)
  {
    printf("fopen(\"out2.log\", \"r\") failed.");
    exit(1);
  }

  fputs("Hello World file2!\n", fd4);

  if (fgets(output_reg, 30, fd3) == NULL)
    printf("fgets returned NULL, feof is %d\n", feof(fd3));
  else
    printf("FILE 2 b4  = output_reg : %s\n", output_reg);

  fflush(fd4);

  if (fgets(output_reg, 30, fd3) == NULL)
    printf("fgets returned NULL, feof is %d\n", feof(fd3));
  else
    printf("FILE 2 af  = output_reg : %s\n", output_reg);
}

You'll see that the first fgets returns NULL and that this sets the end of file flag to 1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM