问题遇到的现象和发生背景
写将文件中数据导入进链表的函数,使用了fscanf的循环,结果执行到这个循环程序就卡死,反复debug后发现执行完一次fscanf循环后第二次无法开始,如何解决?
问题相关代码,请勿粘贴截图
typedef struct HouseSource //房源的链表
{
char name[20]; //房源名
int price; //房源价格
int start; //起租年份
int end; //退租年份
struct HouseSource next;
} housesource;
void init()
{
FILE fp=NULL;
h1=head_h;
housesource* house=h1;
fp=fopen("./housesource.txt","r");
bool t_repeat;
char t_name[20];
int t_price;
int t_start;
int t_end;
while(!feof(fp))
{
if(fscanf(fp,"%s %d %D %d\n",t_name,&t_price,&t_start,&t_end)==0) //此处大写D是因为csdn不允许重复字符
{
fseek(fp,2,1);
}
else
{
h1=(housesource*)malloc(sizeof(housesource));
strcpy(h1->name,t_name);
h1->price=t_price;
h1->start=t_start;
h1->end=t_end;
h1->next=NULL;
house=(housesource*)malloc(sizeof(housesource));
house->next=h1;
house=h1;
}
}
}
void allocation()
{
head_h=(housesource*)malloc(sizeof(housesource));
head_h->next=NULL;
init();
}
int main()
{
allocation();
return 0;
}
运行结果及报错内容
相当于没有结果
我的解答思路和尝试过的方法
上网查找了很多关于fscanf函数的内容,试图用fseek跳过,试图改循环判定,均未果,已经束手无策了
我想要达到的结果
循环能完全读取文件中的数据