C,从文件中读取到结构 [英] C, reading from file into structure
问题描述
我一直在这个挣扎了几天,我想不通为什么它不工作。
我想用这样写的号码来读取文件编号:
0 2012 1 1 2000.000000
0 2012 1 1 3000.000000
2012年1 1 1 4500.000000
我的结构:
结构元素{ INT ID;
INT标志;
INT年;
INT月;
双量; 结构元素*接下来的;
};结构队列{
结构元素*头;
结构元素*尾;
结构元素* HEAD2;
结构元素*温度;
结构元素* temph; INT大小;
};
(HEAD2,温度和temph分拣结构使用)
块引用>和从文件中读取:
无效read_str(结构队列*队列){ FILE *读取; 字符文件名[40];
INT温度; 的printf(类型中的文件\\ n名);
scanf函数(%S,&安培;文件名);
读取=的fopen(文件名,R);
如果(阅读== NULL){
PERROR(错误);
返回1;
}
其他{
而(!的feof(读取)){
结构元素* N =(结构元素*)malloc的(的sizeof(结构件));
的fscanf(读,%D%D%LF,正与GT; ID,正>登录,正>同期,正>当月,正>金额);
正>接着= NULL; 如果(queue->头== NULL){
queue->头= N;
}
其他{
queue-> tail->接下来= N;
} queue->尾= N;
queue->大小++; }
}
}我可以更改数据看起来通过改变其写入功能的文件的方式,但我不认为这是问题。我猜我使用
的malloc
以错误的方式。解决方案的fscanf(读,%D%D%LF,正> ID,正>登录,正>同期,正&GT ;当月,正>金额);
块引用>的
scanf函数
系列函数期望地址。更改的fscanf
行:的fscanf(读,%D%D%LF,&安培; N-> ID,和放大器; N->登录,和放大器; N-&GT ;年,
&安培; N->当月,&安培; N->金额);侧面说明,这是一种严重误导行:
其他{而(!的feof(读取)){
块引用>I've been struggling with this for days and I can't figure out why it doesn't work.
I'm trying to read numbers from file with numbers written like this:
0 2012 1 1 2000.000000 0 2012 1 1 3000.000000 1 2012 1 1 4500.000000
my structure:
struct element{ int id; int sign; int year; int month; double amount; struct element *next; }; struct queue{ struct element *head; struct element *tail; struct element *head2; struct element *temp; struct element *temph; int size; };
(head2, temp and temph are used in sorting structure)
and reading from a file:
void read_str(struct queue *queue){ FILE *reads; char filename[40]; int temp; printf("Type in name of the file\n"); scanf("%s",&filename); reads=fopen(filename, "r"); if (reads==NULL) { perror("Error"); return 1; } else { while(!feof(reads)) { struct element *n= (struct element*)malloc(sizeof(struct element)); fscanf(reads,"%d %d %d %d %lf", n->id, n->sign, n->year, n->month, n->amount); n->next=NULL; if(queue->head ==NULL) { queue->head=n; } else { queue->tail->next=n; } queue->tail=n; queue->size++; } } }
I can change the way the data looks in a file by changing the function that writes it, but I don't think that's the problem. My guess I'm using
malloc
in a wrong way.解决方案fscanf(reads,"%d %d %d %d %lf", n->id, n->sign, n->year, n->month, n->amount);
The
scanf
family of functions expect addresses. Change thefscanf
line to:fscanf(reads,"%d %d %d %d %lf", &n->id, &n->sign, &n->year, &n->month, &n->amount);
Side note, this is a seriously misleading line:
else { while(!feof(reads)) {
这篇关于C,从文件中读取到结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!