how do return a file line number in C, so that I can use a for loop to printf() a sequence of lines from the file?

I pasted my function below, and this is what I want it to do: If strcmp(line, info) == 0 (true), return "file.txt" line number, then printf() line -1 through line +6 from file to terminal. ie. if match is found on line 10, output should be

line 9
line 10
...
line 16

I'm sure there's something wrong with my for loop, as this function is written, it compiles and the program runs, but nothing is printed to the screen if (true).

int check_duplicates(string info)
{

    FILE *fp = fopen("file.txt", "r");
    char line[100];
    int line-number
    while (fgets(line, sizeof(line), fp))
    {
        if (strcmp(line, info) == 0)
        {
            for (int i = (line_number -1); i < (line_number + 6); i++)
            {
                printf("%s\n", line);
            }
            return 1;
        }

    }
    return 0;
}

If someone could help me fix whatever I've done wrong, that would be awesome!

1 answer

  • answered 2022-01-23 03:15 Barmar

    To get the line numbers, use a counter variable that you increment after reading each line.

    To print the line before the match, copy the line into another string, and print that before printing the line and the following 6 lines.

    Assuming info doesn't have a newline at the end, you need to remove the newline from line before comparing it.

    The loop that prints the next 6 lines should just count from 0 to 5, it doesn't need to use anything from line. And it has to call fgets() in the loop to read the lines, otherwise you'll just keep printing the same line.

    int check_duplicates(string info)
    {
    
        FILE *fp = fopen("file.txt", "r");
        char line[100];
        char prev_line[100];
        int line_num = 0;
        while (fgets(line, sizeof(line), fp))
        {
            line[strcspn(line, "\n")] = '\0'; // remove trailing newline
            line_num++;
            if (strcmp(line, info) == 0)
            {
                printf("%d %s\n%d %s\n", line_num-1, prev_line, line_num, line);
                for (int i = 0; i < 6; i++)
                {
                    if (fgets(line, sizeof line, fp)) {
                        printf("%d %s", line_num + i, line);
                    } else {
                        break;
                    }
                }
                fclose(fp);
                return 1;
            }
            strcpy(prev_line, line);
        }
        fclose(fp);
        return 0;
    }
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum