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

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

Essentially, I was wondering if there is a way to do this 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 over the file n-1 times to get to the nth line ... it just doesn't seem very efficient (and if it's homework, I need to get 100% haha).

Any help would be appreciated.

+5
source share
5 answers

, . , , , . , n th.

, , , , . , , .

+7

, fseek .

.

+8

-,

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

:

buffer = malloc(strlen(line) + 1);

+ 1 , "\0"; strlen() . malloc() C , . sizeof(char) 1 , .

targetline, .

, , N- , N-1, . ( , , , , , . ; 10 .)

+5

, n- . . .

+3

If you want to get the nth line from a text file, you need to read the n-1 lines before it. This is the nature of the serial file. If you do not know that all your lines are the same length, there is no way to reliably position the beginning of the first line.

+2
source

All Articles