我試圖從一個文件中將數據輸入到一個結構中,但是每當我嘗試在「文件名」變量中輸入路徑時,它都會給出終端中的段錯誤:當我嘗試打開文件時發生C段錯誤
Goods Re-Order File program Enter database file /stock.txt Segmentation fault
這是我的代碼。此外,我目前正在運行osx 10.5.8,如果這是相關的。
#include <stdio.h>
#include <ctype.h>
#include <string.h>
struct goods
{
char name[20];
float price;
int quantity;
int reorder;
};
FILE *input_file;
void processfile(void);
void getrecord(struct goods *recptr);
void printrecord(struct goods record);
int main(void)
{
char filename[40];
printf("Goods Re-Order File program\n");
printf("Enter database file\n");
scanf("%s",filename);
//strcpy(filename,"/stock.txt");
//gets(filename);
input_file=fopen(filename,"r");
if(!input_file)
{
printf("Could not open file!\n");
}
processfile();
fclose(input_file);
return 0;
}
void processfile(void)
{
struct goods record;
while(!feof(input_file))
{
getrecord(&record);
if(record.quantity<=record.reorder)
{
printrecord(record);
}
}
}
void getrecord(struct goods *recptr)
{
int loop=0,number,toolow;
char buffer[40],ch;
float cost;
ch=fgetc(input_file);
while (ch!='\n')
{
buffer[loop++]=ch;
ch=fgetc(input_file);
}
buffer[loop]=0;
strcpy(recptr->name,buffer);
fscanf(input_file,"%f",&cost);
recptr->price=cost;
fscanf(input_file,"%d",&number);
recptr->quantity=number;
fscanf(input_file,"%d",&toolow);
recptr->reorder=toolow;
}
void printrecord(struct goods record)
{
printf("\nProduct name\t%s\n",record.name);
printf("Product price \t%f\n",record.price);
printf("Product quantity \t%d\n",record.quantity);
printf("Product reorder level \t%d\n",record.reorder);
}
您是否正在輸入超過39個字符?另外,如果'if(!input_file)'測試失敗,你實際上不會退出程序,否則你繼續調用'processfile()',如果'input_file'爲NULL,可能會出現段錯誤。 –
在商品中,名稱爲20個字符,getrecord保留40個字符,但您的循環從不檢查這些界限。 –
'while(!feof(input_file))'如果你在while循環中讀取文件的最後一個元素,你會怎麼想?你將不會讀取文件的結尾,然後當另一個不存在的時候,你會嘗試讀另一個'if(record.quantity <= record.reorder)' – AndyG