2013-04-13 46 views
0

嗨,我想從文件中讀取數據到結構數組的數組我試圖用fgets,但得到的錯誤,指出記錄類型不能轉換爲char *這是我有這麼遠從文件中讀取數據到結構

#include <stdio.h> 
#include <stdlib.h> 

#define MAX_NAME 20 
#define FILE_NAME 50 
#define LIST_SIZE 50 
//void getData(RECORD name[], RECORD score) 


typedef struct RECORD 
{ 
    char *name; 
    float score; 
}RECORD; 


int main (void) 
{ 
    // Declarations 
     FILE *fp; 
     char fileName[FILE_NAME]; 
     RECORD list[LIST_SIZE]; 
     int count = 0; 
    // Statements 
     printf("Enter the file name: "); 
     gets(fileName); 

     fp = fopen(fileName, "r"); 

     if(fp == NULL) 
      printf("Error cannot open the file!\n"); 
     while (fgets(list[count], LIST_SIZE, fp) != NULL) 
     { 
      count++; 
     } 
     return 0; 
} 

錯誤發生在fgets語句內while循環,我該如何解決這個問題,並讀取數據到結構數組?

預先感謝

回答

0

嘗試此,

while(fgets((char *)list[count], SIZE/* data size to be read */, fp) != NULL) 
{...} 
0

與fgets用於輸入從文本文件的一行作爲一個單元的字符串。

例如)

char input_line_buff[128]; 
fgets(input_line_buff, 128, fp); 

讀入

input_line_buff:(內容如) 「的名稱66.6 \ n」 個

你就拆,內存alloc和複製,並轉換。

例如)

list[count].name = strdup("name"); 
list[count].score= atof("66.6"); 
count++;