我不断遇到细分错误,不知道为什么

hai海

我正在用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);
}
泛光灯

您的循环可能无法避免第一个条目NULL,请尝试使用以下循环浏览链表:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

我不断得到细分错误:11错误,我不知道为什么... c ++

不知道为什么我在这里遇到细分错误

PyGame不断崩溃,我不知道为什么

我不断收到此错误消息,但我不知道为什么

我在 CSS 中不断收到此错误,但我不知道为什么

我使用 Flask 在 python 中遇到语法错误,我不知道为什么

SMTP 错误,我不知道为什么

Dockerfile 错误的目录。我不知道为什么

不知道为什么我收到 StopIteration 错误

我的代码中不断出现“未捕获范围”错误,但我不知道为什么

我在 tkinter 'bad window path name .!button2' 中遇到错误,我不知道为什么?

GitHub不断抛出“无法提交子模块”错误,我不知道为什么。有任何想法吗?

带有boto3的AWS Lambda Python S3,不知道为什么我遇到错误

我的豆荚不断重启,我不知道为什么

我不断收到 SyntaxError 但我不知道为什么

我不知道为什么我不断收到 AttributeError: 'tuple' object has no attribute 'size'

我的豆荚不断重启,我不知道为什么

我遇到内存泄漏,但我不知道为什么

Python SimpleHTTPServer不断下降,我不知道为什么

编程新手,遇到运行时错误不知道为什么

我不知道为什么我收到以下错误“错误:元素类型无效:”

我不知道为什么我得到AttributeError

我的陈述无效,我也不知道为什么

我不知道为什么我的代码是错误的?那是什么错呢?

我的代码给了我一个元组错误,我不知道为什么

我尝试测试用Go语言编写的代码,但我不断收到此错误,但我不知道为什么

我收到这个 Intent 的错误,我不知道为什么

我不知道为什么我得到这个文件,但是仍然显示错误

我不知道为什么我在 jsp 文件中收到这个简单代码的错误