使用 fgets() 读取和存储
我正在使用 fgets 从简单文件(例如 txt 文件)读取文本,但是我需要能够跳回到前一行。有没有办法使用 fgets 来做到这一点?或者我应该将文本存储在某种数组/结构中?
I'm using fgets to read in text from simple files such as txt files however I need the ability to jump back to previous lines. Is there anyway to do this using fgets? Or should I just store the text in some sort a array/structure?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
fseek
或fgetpos
和fsetpos
是合适的。 AFAIK,没有“转到 X 行”功能;您必须保存有关每行的一些信息(例如其起始位置),而使用fseek
或fsetpos
来移动。fseek
or a combination offgetpos
andfsetpos
would be appropriate. AFAIK, there is no "go to line X" function; you'll have to save some information about each line (e.g. its starting position) instead, usingfseek
orfsetpos
to move around.您也许可以通过
fseek()
和朋友 ( http://linux.die.net/man/3/fseek)。但是,将“fseek”函数与文本文件混合(尤其是在读取和写入同一流时)可能会由于换行符的库转换而导致问题。
如果你的记忆不是太紧张,我会选择保存前几行的信息。
更好的是,如果可能的话,检查您的算法/数据结构,这样您就不需要返回。
You may be able to solve your problems with
fseek()
and friends ( http://linux.die.net/man/3/fseek ).However, mixing the "fseek" functions with text files (especially if you're reading and writing to the same stream) may cause problems due to the library translation of line breaks.
If you're not too tight on memory, I'd go with saving information from previous lines.
Better yet, if possible review your algorithm/data structure so that you don't need to go back.