Question

I have the following basket.txt file

Center
defence=45
training=95

Shooter
points=34
Rebounds=7

Shooter
points=8
Rebounds=5

Forward
points=8
Rebounds=5

I want to get and display only the Shooter values. To return something like this:

Shooter
points=34
Rebounds=7

Shooter
points=8
Rebounds=5

My thought is to read the file line by line and with the usage of strstr when it finds the string shooter then to print everything above it. But with the following code

int main()
{
  static const char filename[] = "basket.txt";
  FILE *file = fopen (filename, "r");
if (file!= NULL)
{
    char line[128];
    while (fgets (line, sizeof line, file)!= NULL)
    {
        char *line1 = strstr(line,"Shooter");
        if (line1)
        {
        while (fgets (line, sizeof line, file)!= NULL)
        fputs(line,stdout);
        }
    }
fclose(file);
}
else
{
    perror(filename);
}
return 0;
}

it returns me

Shooter
points=34
Rebounds=7

Shooter
points=8
Rebounds=5

Forward
points=8
Rebounds=5

So how can I change my code to have the result which I want?

UPDATE

I changed the while loop

while (fgets (line, sizeof line, file)!= NULL)
    {
        char *line1 = strstr(line,"Shooter");
        if (line1)
        {
            fgets (line, sizeof line, file);
            while (line[0] != '\n')
            {
                fputs(line,stdout);
                fgets (line, sizeof line, file);
                break;
            }

but the results are now

points=34
points=8

It does not return me the rebounds of the Shooters.

Was it helpful?

Solution

if (line1)
{
    while (fgets (line, sizeof line, file)!= NULL)
    fputs(line,stdout);
}

This is wrong, since fgets() doesn't return NULL until the end-of file. You want to read until an empty line is encountered:

if (line1) {
    fgets(line, sizeof line, file);
    while (line[0] != '\n') {
        fputs(line, stdout);
        fgets(line, sizeof line, file);
    }
}

OTHER TIPS

Your inner loops finds the first Shooter and then prints the rest of the file.

The inner loop must stop at the first blank line. Something like:

while ( line[0] != '\n' )
{
    fputs...
    if ( fgets(...) == NULL )
        break;
}

This is well behaved on EOF conditions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top