当逐行浏览文本文件时,我希望能够向前看下一行并在处理当前行时检查它。我在使用C语言。我相信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\n",
line, nextline);
}
我感谢任何帮助。
答案 0 :(得分:0)
以下代码的灵感来自@ Jean-François Fabre comment。它将使用用于保持线条的2D字符数组lineBuffer
。第一个读取行写入索引0 lineBuffer[0]
,第二行写入lineBuffer[1]
。之后,在toggle variable lineSel
的帮助下,着作在索引0和1之间交替。最后一步,curLine
指针将设置为nextLine
。
结果,您可以在循环中使用curLine
和nextLine
。
如果您的文件包含:
line 1
line 2
line 3
...
您将使用:
curLine = "line 1\n"
nextLine = "line 2\n"
curLine = "line 2\n"
nextLine = "line 3\n"
...
请参阅live example with stdin instead of a file on ideone。
<强>代码:强>
#include <stdio.h>
#define BUFMAX 256
#define CURLINE 0
#define NEXTLINE 1
#define TOGGLELINE (CURLINE ^ NEXTLINE)
int main ()
{
FILE* fp = fopen("test-seeking.txt", "r");
char lineBuffer[2][BUFMAX];
char* curLine;
char* nextLine;
int lineSel;
if (fp != NULL)
{
if ((curLine = fgets(lineBuffer[CURLINE], BUFMAX, fp)))
{
for (lineSel = NEXTLINE;
(nextLine = fgets(lineBuffer[lineSel], BUFMAX, fp));
lineSel ^= TOGGLELINE)
{
printf("Current line: \"%s\" / Next line \"%s\"\n",
curLine, nextLine);
curLine = nextLine;
}
}
fclose(fp);
}
return 0;
}
答案 1 :(得分:0)
确实你可以使用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\n", 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\n", line, nextline);
}