fpI不知道为什么会出现seg fault,我正确地关闭文件,保持在循环的链表中,但是当它到达for循环或while fgets循环(这两个循环之一)时,它会出现seg fault。我有一个非常相似的函数,工作得很好,我从中修改了这个,但是它不会产生相同的输出
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;
}
}
}
最佳答案
变量filecheck
尚未初始化。
char* filecheck;
....
if ( strcmp(ptr->fileName, filecheck) != 0 ) {
它需要被设置成一些东西。
char* filecheck = "";
关于c - 从链接列表(C)打印值段错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28617390/