我试图从一个文件中将数据输入到一个结构中,但是每当我尝试在“文件名”变量中输入路径时,它都会给出终端中的段错误:当我尝试打开文件时发生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