CRS
CRS

Reputation: 837

trying to print a line a text file in c

i am trying to print a line from a text file then go to the next line and print that until there is no more lines left to print. This is what i have so far, but it only works the first time that i run the program.

void ReadFile(FILE *a)
{
    char line[23];
    while(fgets(line, 22, a) != NULL)
    {
        printf("%s", line);
    }
}

Upvotes: 1

Views: 3674

Answers (2)

Alexander
Alexander

Reputation: 8147

You're not rewind(a)ing the file and so every iteration of the function begins from where the last fgets left it (EOF, in your case).

Upvotes: 1

trojanfoe
trojanfoe

Reputation: 122391

You will need to reset the file pointer back to the start if you want to do this multiple times with the same FILE object:

void ReadFile(FILE *a)
{
    char line[23];
    rewind(a);
    while(fgets(line, 22, a) != NULL)
    {
        printf("%s\n", line);    // Added new line
    }
}

Reference.

Upvotes: 7

Related Questions