简体   繁体   English

fgets 如何从文件中一行一行地读取?

[英]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 ?但是在 while 循环中, fgets获得相同的参数 - 那么它如何知道在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编辑:添加了额外的解释,因为@KlasLindbäck 指出我的答案并不完全正确

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. File 是一个结构体,其中包含一个字段“fd”,它是一个整数,用于标识此文件的 OS 文件描述符,此文件描述符可用于检索您正在读取的文件中的当前位置。 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. TL;DR:FILE 结构以某种方式存储它正在读取的位置。

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() .您可以使用ftell()获取当前位置并使用fseek()设置当前位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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