我一直遇到分段错误,我不知道为什么

时间:2016-04-18 23:27:33

标签: c

我正在用C编写一个链表程序,我试图将链表写入文件。在程序询问用户他们想要保存文件的名称之后,我输入名称并按Enter键然后我得到分段错误并退出程序。我迷失了,试图找出原因。我唯一能想到的是do..while循环,但我在我的程序中使用其他代码,它工作正常。提前谢谢!

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Inventory {
    int partID;
    int quantity;
    float price;
    struct Inventory *next;
};

void saveFile(struct Inventory**);

int main()
{
    struct Inventory *first = address location of first structure in list;

    saveFile(&first);

    return 0;
}

void saveFile (struct Inventory **firstPtr)
{
    struct Inventory *prev = NULL;
    char ext[5] = ".csv";
    char fileName[15];
    char c;

    FILE *fp;

    printf("   What would you like to save your linked list as, up to 14 characters: ");
    scanf("%s", fileName);
    strcat(fileName, ext);

    if((fp = fopen(fileName, "r")) != NULL) {
        printf("   File already exists. Would you like to overwrite? [Y/N] ");
        scanf("\n%c", &c);

        if(c == 'Y' || c == 'y') {
           fclose(fp);
           fp = fopen(fileName, "w+");
        } else {
           printf("   Would you like to add to the list? [Y/N] ");
           if(c == 'y' || c == 'Y') {
               fclose(fp);
               fp = fopen(fileName, "a");
           } else {
               fclose(fp);
               return;
           }
        }

    } else {
        fclose(fp);
        fp = fopen(fileName, "w+");
    }   

    do {
        prev = *firstPtr;
        fprintf(fp, "%d,%d,%f\n", prev->partID, prev->quantity, prev->price);
        prev = prev->next; 
    } while (prev->next != NULL); 

    fclose(fp);
}

1 个答案:

答案 0 :(得分:3)

你的循环没有防止第一个条目可能是NULL,尝试使用以下循环链接列表:

while (prev) {
    fprintf(fp, "%d,%d,%f\n", prev->partID, prev->quantity, prev->price);
    prev = prev->next;
}