2

In the following C-code I open a file called test.txt which contains a few lines. I then read in those lines in a while-loop and print them to stdout. Afterwards I make a few changes in the file by e.g. appending the number 42 to it. I then want to print the contents of the changed file to stdout but I seem to missing something there. Here is my code so far (unnecessarily commented):

#include <stdio.h>
#include <stdlib.h> /* for exit() */

main ()
{   /* Declare variables */
    FILE *file_read;
    char file_save[100];
    int number = 42;

    /* Open file */
    file_read = fopen("/home/chb/files/Cground/test.txt", "a+");

    /* Check if file exists. */
    if (file_read == NULL) {
        fprintf(stderr, "Cannot open file\n");
        exit(1);
    }

    /* Print what is currently in the file */
    printf("This is what is currently in the file:\n");
    while(fgets(file_save, 100, file_read) != NULL) {
    printf("%s", file_save);
    }

    /* Change the contents of the file */
    fprintf(file_read, "%d\n", number);

    /* Print what is in the file after the call to fscanf() */
    printf("This is what is now in the file:\n");
    /* Missing code */
    fclose(file_read);
}

It seems that a simple while-loop placed where Missing code is, similar to the one already used before will not suffice. Can someone please explain what is going on. I don't mind technicalities!

lord.garbage
  • 5,884
  • 5
  • 36
  • 55

2 Answers2

1

You do not set the file pointer back to start. As it's already at the end of the file, there's nothing more to read. Before reading the file again, do:

rewind(file_read); //before the "missing code" comment 

to set it back at the start of the file.

P.P
  • 117,907
  • 20
  • 175
  • 238
  • Thanks. I chose @pfannkuchen_gesicht's solution after I read [fseek vs rewind](https://stackoverflow.com/questions/11839025/fseek-vs-rewind). Fseek has the advantage of returning success which `rewind()` does not. – lord.garbage May 01 '15 at 13:55
  • Agree, `fseek` does have that advantage over `rewind`. – P.P May 01 '15 at 16:09
1

In order to read the file from the start again you have to call fseek() first, like so

fseek(file_read, 0, SEEK_SET);

this sets the stream position indicator back to the start of the file.

See http://www.cplusplus.com/reference/cstdio/fseek/ for more info.

rfreytag
  • 1,203
  • 11
  • 18