fhaoebJebwoqbxoqh
fhaoebJebwoqbxoqh

Reputation: 11

Scan a second line from a file

Line 1
Line 2
Line 3

I want to scan the second line with fgets. How may I do so? How do I scan specific lines from a file?

Upvotes: 0

Views: 52

Answers (1)

Andreas Wenzel
Andreas Wenzel

Reputation: 25281

It is not possible to jump to a specific line directly. However, you can create a function which reads the file from the beginning until it finds a certain number of newline characters, so that the file position will be at the start of that specific line once the function returns:

#include <stdio.h>
#include <string.h>
#include <stdbool.h>

// This function returns true on success, false on failure
bool go_to_nth_line( FILE *fp, int line_num )
{
    //jump to start of file
    if ( fseek( fp, SEEK_SET, 0 ) != 0 )
        return false;

    //loop until the required number of newline characters was found
    for ( int i = 1; i < line_num; i++ )
    {
        char buffer[4096];

        //continue reading until newline character is found
        do
        {
            if ( fgets( buffer, sizeof buffer, fp ) == NULL )
                return false;

        } while ( strchr( buffer, '\n' ) == NULL );
    }

    return true;
}

Upvotes: 1

Related Questions