Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Programming - Read specific line from text file

Tags:

c

file-io

Here is the code:

int main()
{
    struct vinnaren
    {
        char vinnare[20];
        int artal;
    };
    struct vinnaren v[10];
    int inputrader;
    int antalrader;  //I want antalrader to be equal to the first 
                     //line in test.txt(the first line is "5")
    char file_name[256] = "test.txt";
    char buf[512];
    FILE *f = fopen(file_name, "r");
    if (!f)
    {
        exit(0);
    }
    while (fgets(buf, sizeof buf, f))
    {

        printf("%s", buf);
    }
    fclose(f);
}

This is the code I have. I want to make it so that antalrader = line1 in the file test.txt How do I read a specific line from the file?

like image 446
Krippkrupp Avatar asked Jan 14 '14 13:01

Krippkrupp


People also ask

How do you read and print a string from a file in C?

Steps To Read A File:Open a file using the function fopen() and store the reference of the file in a FILE pointer. Read contents of the file using any of these functions fgetc(), fgets(), fscanf(), or fread(). File close the file using the function fclose().

Does Fgets read line by line?

The C library function char *fgets(char *str, int n, FILE *stream) reads a line from the specified stream and stores it into the string pointed to by str. It stops when either (n-1) characters are read, the newline character is read, or the end-of-file is reached, whichever comes first.


1 Answers

With this code you can read a file line by line and hence read a specific line from the text file:

lineNumber = x;

static const char filename[] = "file.txt";
FILE *file = fopen(filename, "r");
int count = 0;
if ( file != NULL )
{
    char line[256]; /* or other suitable maximum line size */
    while (fgets(line, sizeof line, file) != NULL) /* read a line */
    {
        if (count == lineNumber)
        {
            //use line or in a function return it
            //in case of a return first close the file with "fclose(file);"
        }
        else
        {
            count++;
        }
    }
    fclose(file);
}
else
{
    //file doesn't exist
}
like image 157
invalid_id Avatar answered Oct 21 '22 16:10

invalid_id