gpt4 book ai didi

c - 处理输入文件时如何向前看(处理 2 行)

转载 作者:太空宇宙 更新时间:2023-11-04 04:21:59 25 4
gpt4 key购买 nike

当逐行浏览文本文件时,我希望能够向前看下一行并在处理当前行时检查它。我正在使用 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);
}

感谢任何帮助。

最佳答案

事实上,您可以使用 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);
}

另一种方法是使用fgetposfsetpos,如下所示:

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);
}

关于c - 处理输入文件时如何向前看(处理 2 行),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45938222/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com