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!