简体   繁体   English

fscanf()和fgets()这样的函数如何记住文件中的哪些内容开始读取?

[英]How do functions like fscanf() and fgets() remember where in the file to start reading from?

For instance, when reading a file using fscanf() , it seems to remember where it last left terminated, rather than starting from the beginning of the file again. 例如,当使用fscanf()读取文件时,它似乎记住它最后一次终止的位置,而不是再次从文件的开头开始。 Can someone please elaborate on how exactly this works? 有人可以详细说明这是如何工作的吗? I've finding it difficult to use these functions, since I do not understand this component. 我发现很难使用这些功能,因为我不理解这个组件。

The FILE * parameter points to a buffer and a file handle (see the fileno() function). FILE *参数指向缓冲区和文件句柄(请参阅fileno()函数)。

The actual where is remembered in the kernel in the file structure. 实际在文件结构中的内核中记住的位置。

There is a legend that the FILE * pointer points into the file. 有一个图例, FILE *指针指向文件。 This is not literally true, but it might as well be true for the interpretation of the beginning programmer. 这不是字面意义,但对于初级程序员的解释可能也是如此。

In fact what happens is as follows: Every process has an array in kernel of type struct file (this type is not defined in userspace so don't go looking for it) that contains all of its open files. 实际上发生的事情如下:每个进程在struct file内核中都有一个数组(这种类型没有在用户空间中定义,因此不要去查找它),其中包含所有打开的文件。 A handle is returned by the open() syscall that is merely an index into the array. 一个句柄由open()系统调用返回,它只是数组的索引。 The function fileno() retrieves the handle from the FILE * pointer returned by fopen() and can be manipulated directly. 函数fileno()fopen()返回的FILE *指针中检索句柄,可以直接操作。 This is usually a bad idea except for accessing ioctl() or fctl() as you will end up fighting with the internal buffer in the FILE object. 除了访问ioctl()fctl()之外,这通常是一个坏主意,因为您最终将与FILE对象中的内部缓冲区进行战斗。

One of the members of struct file is loff_t f_pos which is the exact location in bytes the kernel read() or write() stopped at. struct file一个成员是loff_t f_pos ,它是内核read()write()停止的确切位置(以字节为单位write() This is buffered in FILE which knows how many bytes it read ahead or pended for a later write for you. 这是在FILE中缓冲的,它知道它前面读取的字节数或后续写入的字节数。

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

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