Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fgets() a specific line from a file in C?

So, I'm trying to find a way to fgets() a specific line in a text file in C, to copy the contents of the line into a more permanent buffer:

Essentially, I was wondering if there was a way to do that without something similar to the following code:

FILE *fp;
fp = fopen(filename, "r");

char line[256];
char * buffer;
int targetline = 10;
while( targetline > 0)
{
    fgets(line, 256, fp)
}

buffer =(char*)malloc(sizeof(char) * strlen(line));
strcpy(buffer, line);

So basically I don't want to iterate through the file n-1 times just to get to the nth line... it just doesn't seem very efficient (and, this being homework, I need to get a 100% haha).

Any help would be appreciated.

like image 336
gfppaste Avatar asked Nov 17 '11 22:11

gfppaste


People also ask

How do you get a specific line in a file in 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.

How do I read a line in fgets?

The fgets() function reads characters from the current stream position up to and including the first new-line character (\n), up to the end of the stream, or until the number of characters read is equal to n-1, whichever comes first.

Does fgets read one line?

fgets method can read the first line but when it comes to the second line, it cannot read neither the second line nor the rest of the file (since it exits when a problem occurs).


1 Answers

Unless you know something more about the file, you can't access specific lines at random. New lines are delimited by the presence of line end characters and they can, in general, occur anywhere. Text files do not come with a map or index that would allow you to skip to the nth line.

If you knew that, say, every line in the file was the same length, then you could use random access to jump to a particular line. Without extra knowledge of this sort you simply have no choice but to iterate through the entire file until you reach your desired line.

like image 159
David Heffernan Avatar answered Sep 25 '22 20:09

David Heffernan