2012-07-01 24 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)'。這樣你就知道你已經讀完整個結構。 –