C : Best way to go to a known line of a file

Viewed 2628

I have a file in which I'd like to iterate without processing in any sort the current line. What I am looking for is the best way to go to a determined line of a text file. For example, storing the current line into a variable seems useless until I get to the pre-determined line.

Example :

file.txt

foo
fooo
fo
here

Normally, in order to get here, I would have done something like :

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

But fgetswill have to read fully three line uselessly and currentLine will have to store foo, fooo and fo.

Is there a better way to do this, knowing that here is line 4? Something like a go tobut for files?

4 Answers
Related