2012-07-01 25 views
3

我一直在挣扎着这几天,我无法弄清楚为什么它不起作用。C,从档案中读取到结构中

我试图用这样写的号码从文件中读取数据:

0 2012 1 1 2000.000000 
0 2012 1 1 3000.000000 
1 2012 1 1 4500.000000 

我的结构:

​​

(HEAD2,温度和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

回答

18
fscanf(reads,"%d %d %d %d %lf", n->id, n->sign, n->year, n->month, n->amount); 

scanf家庭的功能期待地址。在fscanf行更改为:

fscanf(reads,"%d %d %d %d %lf", &n->id, &n->sign, &n->year, 
    &n->month, &n->amount); 

方面说明,这是一个严重的误导行:

else { while(!feof(reads)) { 
+0

谢谢,它帮助! 为什么我不应该使用'else {while(!feof(reads)){'? – ozech

+2

@ozech迟到的答案,但不应该使用feof(),因为它只会在您试图读取文件末尾之后返回false。有可能只读取一部分可能不是你想要的结构。您的循环也可能会执行额外的时间。你应该检查一下,看看fscanf返回的值是'> = sizeof(your_struct)'。这样你就知道你已经读完整个结构。 –