我很久以来一直在苦苦挣扎,但是我无法弄清楚为什么它不起作用。
我正在尝试从文件中读取数字,这些数字的书写方式如下:
0 2012 1 1 2000.000000
0 2012 1 1 3000.000000
1 2012 1 1 4500.000000
我的结构:
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和temph用于排序结构)并从文件中读取:
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++;
}
}
}
我可以通过更改编写数据的函数来改变文件中数据的外观,但我不认为那是问题所在。我猜测我错误地使用了malloc
。
else { while(!feof(reads)) {
? - ozech>= sizeof(your_struct)
。这样你就知道已经读入了整个结构体。 - Alex Vallejo