Search code examples
cfgets

How fgets reads line after line from a file?


Let say I have:

#define CHUNK_SIZE 256

void copy(FILE *input, FILE *output) {
     char buffer[CHUNK_SIZE];
     while (fgets(buffer, CHUNK_SIZE, input) != NULL) {
          fputs(buffer, output);
     }
}

But in the while loop, fgets gets the same parameters - so how does it know to read the next line from the file in each iteration of while? Doesn't it suppose to get stuck in infinite loop because it always reads the same line?


Solution

  • EDIT: added extra explanation as @KlasLindbäck pointed out that my answer wasn't entirely correct

    The File is a struct that contains a field "fd" which is an integer that identifies the OS file descriptor of this file, this file descriptor can be used to retrieve the current location in the file you're reading. If you want more information about the File struct here and file descriptor here

    TL;DR: The FILE struct somehow stores where it's reading.