简体   繁体   中英

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!

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 %d\n", line_num-1, prev_line, line_num, line);
            for (int i = 0; i < 6; i++)
            {
                if (fgets(line, sizeof line, fp)) {
                    printf("%d %d", line_num + i, line);
                } else {
                    break;
                }
            }
            return 1;
        }
        strcpy(prev_line, line);
    }
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM