从链表 (C) 打印值时出现段错误

Segfault on printing values from linked list (C)

fp我不知道为什么这会出现段错误,我正确地关闭了文件,我留在循环的链表中,但是当它进入 for 循环或 while fgets 循环(两个之一) 它会出现故障。我有一个非常相似的功能,可以完美运行,我从中修改了它,但它不会产生相同的输出

static int wordMode(struct node *head, char* word)
{
    struct node *ptr;
    int count = 0;
    char* filecheck;
    char* tester;
    ptr = head;

    //print the lines
    for (ptr = head; ptr != NULL; ptr = ptr->next){
        if ( strcmp(ptr->fileName, filecheck) != 0 ) {
            filecheck = ptr->fileName;
            printf("=====================%s\n", filecheck);

            //if new file, open it and start printing
             FILE *fp = fopen(ptr->fileName, "r");
                char line [ 1024 ]; /* or other suitable maximum line size */
                int counter = 1;
                while ( fgets ( line, sizeof line, fp ) != NULL ) /* read a line */{
                     //check if the line number is in the linked list, if so add match
                     printf(" %d: %s", counter, line); /* write the line */
                     counter++;
                  }
                  fclose ( fp );
        } 
        else{
            continue;
        }
    }
}

你指向 File *file 的指针不叫 fp。它是文件。 而且 fclose(fp) 应该是 fclose(file)

变量filecheck尚未初始化。

char* filecheck;
....

    if ( strcmp(ptr->fileName, filecheck) != 0 ) {

需要设置一些东西。

char* filecheck = "";