如何在处理输入文件时向前看(处理2行) [英] How to peek ahead when processing an input file (processing 2 lines)
本文介绍了如何在处理输入文件时向前看(处理2行)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
fseek()
或其他类似的功能会对我有帮助,但我不确定,也不知道如何使用它们。我想取得的成就是:
fp = fopen("test-seeking.txt", "r");
while((fgets(line, BUFMAX, fp))) {
// Peek over to next line
nextline = ...;
printf("Current line starts with: %-3.3s / Next line starts with %-3.3s
",
line, nextline);
}
感谢您的帮助。
推荐答案
确实可以使用fseek
并尝试这样的操作:
fp = fopen("test-seeking.txt", "r");
while ((fgets(line, BUFMAX, fp))) {
// Get the next line
fgets(nextline, BUFMAX, fp);
// Get the length of nextline
int nextline_len = strlen(nextline);
// Move the file index back to the previous line
fseek(fp, -nextline_len, SEEK_CUR); // Notice the - before nextline_len!
printf("Current line starts with: %-3.3s / Next line starts with %-3.3s
", line, nextline);
}
另一种方法是使用fgetpos
和fsetpos
,如下所示:
fp = fopen("test-seeking.txt", "r");
while ((fgets(line, BUFMAX, fp))) {
// pos contains the information needed from
// the stream's position indicator to restore
// the stream to its current position.
fpos_t pos;
// Get the current position
fgetpos(fp, &pos);
// Get the next line
fgets(nextline, BUFMAX, fp);
// Restore the position
fsetpos(fp, &pos);
printf("Current line starts with: %-3.3s / Next line starts with %-3.3s
", line, nextline);
}
这篇关于如何在处理输入文件时向前看(处理2行)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文