保存当前的读取位置,以便我可以在以后查找 [英] Saving off the current read position so I can seek to it later

查看:119
本文介绍了保存当前的读取位置,以便我可以在以后查找的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序可以读取具有已知结构的文本文件。

I have a program that reads a text file which has a known structure.

例如,我在文件的每一行都有两个整数和一个字符串。

For example, I have two integers and one string on each line of the file.

当我在循环中使用 fscanf 时,我可以重新获得 n 如上所述的结构。如何在数据文件中获取当前位置,因此我将其存储在某处,然后继续从我之前离开的位置继续读取我的文本文件。

When I use fscanf inside a loop, I can regain n structures such as I mentioned above. How do I get my current position in the data file, so I store it somewhere, and then later continue reading my text file from where I left off earlier.

推荐答案

使用ftell()函数。它将返回文件中的偏移量。

Use the ftell() function. It will return the offset in the file.

unsigned long position = ftell(file);

但是,对于文本文件,知道ftell()可以报告错误的位置非常重要除非内部缓冲区已被清除。为此,

However, with text files, it is very important to know that ftell() can report the wrong position unless the internal buffer has been cleared. To do this,

unsigned long position;
fflush(file);
position = ftell(file);

稍后,您可以使用fseek

Later, you can use fseek

fseek(file,position,SEEK_SET);

ftell()告诉我们使用前面文件开头的偏移量。在这里,你使用SEEK_SET来表示你传递的位置是从文件的开头。

ftell() told use the offset from the beginning of the file earlier. Here, you use SEEK_SET to indicate that the position you're passing is from the beginning of the file.

编辑:理查德询问fflush()的作用。在读取或写入文件时,C库几乎总是保留信息的缓冲区。 刷新该缓冲区是将其写入磁盘,以保存任何更改。由于允许C库处理文本文件的方式,除非刷新缓冲区,否则此缓冲区可能会导致ftell()报告错误的位置。这就是fflush()的作用。

Richard asked what fflush() does. When you are reading or writing a file, the C library is almost always keeping a buffer of the information. To "flush" that buffer is to write it out to disk, to save any changes. Because of the way the C library is allowed to treat text files, it is possible that this buffer can cause ftell() to report the wrong position unless the buffer is flushed. That is what fflush() does.

这篇关于保存当前的读取位置,以便我可以在以后查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆