简体   繁体   中英

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?

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.

An open file internally keeps track of the current position for the next read operation. Whenever you read from the file the position is updated. You can get the current postition with ftell() and set the current position with fseek() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM