我正在用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] 删除。
我来说两句