1

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);

}
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115

1 Answers1

1

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.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
  • Actually I just realized that I misunderstood your question, and therefore my answer might not apply. But anyway run the code in the answer and tell us what the output. – Jabberwocky Mar 04 '21 at 08:24
  • below is the output. fgets returned NULL, feof is 1 fgets returned NULL, feof is 1 – Arvind Kumar Soni Mar 04 '21 at 11:07
  • [Edit](https://stackoverflow.com/posts/66470740/edit) your question and put all relevant information _there_. You cannot format comments properly for multiline content – Jabberwocky Mar 04 '21 at 11:11