Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 307
Badda Avatar asked May 29 '17 14:05

Badda


People also ask

How do you go to a specific line in a file C?

You can use fgets [^] in a loop to read a file line by line. When no more lines can be read, it will return NULL. On the first line you can use sscanf[^] to extract the integer.

Does Fscanf read line by line?

The fscanf reads until it meats \n (new line) character ,whereas you can use fgets to read all lines with the exact same code you used! Hope that helped :) Save this answer.

How do I move a pointer to a particular line in CPP?

The fsetpos() function moves the file position indicator to the location specified by the object pointed to by position. When fsetpos() is executed ,the end-of-file indicator is reset. stream – This is the pointer to a FILE object that identifies the stream.


1 Answers

Since you do not know the length of every line, no, you will have to go through the previous lines.

If you knew the length of every line, you could probably play with how many bytes to move the file pointer. You could do that with fseek().

like image 90
gsamaras Avatar answered Oct 30 '22 09:10

gsamaras