我有一个文件,我想遍历它,但不处理当前行。我要找的是在文本文件中定位到特定行的最佳方法。例如,将当前行存储到变量中似乎没有用,直到我到达预定的行。
示例:
file.txt
foo
fooo
fo
here
通常,要达到这个目的,我会执行以下操作:
FILE* file = fopen("file.txt", "r");
if (file == NULL)
perror("Error when opening file ");
char currentLine[100];
while(fgets(currentLine, 100, file))
{
if(strstr(currentLine, "here") != NULL)
return currentLine;
}
但是fgets
必须无用地读取三行,并且currentLine
必须存储foo
,fooo
和fo
。
有没有更好的方法来做到这一点,知道here
是第4行? 例如文件的go to
?
fseek
偏移量索引。(这很简单,但需要一些工作。) - Steve Summit