0

I'm trying to create a file, write in it, then read it and print out what was read. I'm trying to use the w+ mode but the output gives infinite lines of null. What am I doing wrong?

 int main() {
    FILE *fPointer;
    char line[10];

    fPointer = fopen("newFile.txt","w+");
    fprintf(fPointer, "Hello\nWorld\n!");

    while (!feof(fPointer)) {
        fgets(line, 10, fPointer);
        puts(line); 
    }

    fclose(fPointer);

    return 0;
} 
1Disciple
  • 1
  • 1
  • 3
    Possible duplicate of [Why is “while ( !feof (file) )” always wrong?](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – cleblanc Aug 07 '18 at 20:09
  • 1
    If you want to read back what you wrote to file, you must use `rewind` or `fseek` before reading, and then, control the loop with the result of `fgets`, such as `while(fgets(...) != NULL) { ... }` – Weather Vane Aug 07 '18 at 20:11
  • 2
    After you've written, the file pointer is positioned at the EOF. To read what you wrote, you must rewind the file — `rewind()` or `fseek()` or one of their relatives. Some file positioning operation is required every time you switch between reading and writing or between writing and reading — even if it is a no-op `fseek(fp, 0, SEEK_CUR)`. – Jonathan Leffler Aug 07 '18 at 20:14
  • @cleblanc Why doesn't this terminate then? Does EOF not get set (after the fact) for 'w+' files? – Max Aug 07 '18 at 20:44
  • 2
    @cleblanc that link is relevant but it is not a duplicate. (The main problem is reading after writing without a seek) – M.M Aug 07 '18 at 21:35

1 Answers1

2

You are violating 7.21.5.3 The fopen function, paragraph 7 of the C standard:

When a file is opened with update mode ('+' as the second or third character in the above list of mode argument values), both input and output may be performed on the associated stream. However, output shall not be directly followed by input without an intervening call to the fflush function or to a file positioning function (fseek, fsetpos, or rewind), and input shall not be directly followed by output without an intervening call to a file positioning function, unless the input operation encounters end- of-file.

This likely explains why the while (!feof(fPointer)) loop does not terminate. As incorrect as your usage is there, it does normally terminate. By ignoring the return value from fgets() (among all the other return values ignored) you are likely missing an error being returned.

Since you have not provided any details regarding your implementation, it's impossible for an outside observer to know for sure.

Andrew Henle
  • 32,625
  • 3
  • 24
  • 56