尝试在C中加载文件时出现分段错误

时间:2017-05-07 23:13:10

标签: c file segmentation-fault

我无法弄清楚为什么会出现分段错误错误。非常感谢任何帮助!

AddressBookList * commandLoad(char * fileName)
{
AddressBookList * list;
AddressBookNode * node;

char line[MAX_LINE_LENGTH];
char *ptr;
int id;
char *name;

FILE * fp = fopen(fileName, "r");
printf(">Opening the file %s.\n", fileName);
if(fp == NULL){
    printf(">Error: Unable to find the specified file. ");
    fclose(fp);
    return NULL;
}
else{
    printf(">Loading the file ...\n");
    list = createAddressBookList();
    while(fgets(line,MAX_LINE_LENGTH,fp) != NULL){
        if(line[0]!= '#'){
            id = (int)strtol(strtok(line,", "), &ptr, 0);
            name = strtok(NULL,",\n");
            node = createAddressBookNode(id,name);
            if(list->size == 0){
                list->head = node;
                list->current = list->head;
                node->nextNode = NULL;
                node->previousNode = NULL;
            }
            else{
                node->previousNode = list->tail;
                node->previousNode->nextNode = node;
            }
            list->tail = node;
            list->size++;
            printf("%d,%s\n",node->id,node->name);
        }
    }
    printf(">%d phone book entries have been loaded from the file.\n",list->size);
    printf(">Closing the file.\n");
}
fclose(fp);
return list;

}

AddressBookList * createAddressBookList()
{
   AddressBookList * list = malloc(sizeof(AddressBookList));
   return list;
}

我将argv从main传递给commandLoad并尝试在此函数中加载该文件。下面是函数以及createAddressBookList的函数,以防我在那里丢失一些东西。函数createAddressBookNode不包含在内,因为它的工作原理与list相同。

0 个答案:

没有答案