【问题标题】:read data from file into array of structures将文件中的数据读入结构数组
【发布时间】:2013-04-13 06:33:08
【问题描述】:

您好,我正在尝试将文件中的数据读取到结构数组中,我尝试使用 fgets 但收到错误消息,说 RECORD 类型无法转换为 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;
}

错误发生在while循环内的fgets语句中,我该如何解决这个问题并将数据读入结构数组?

提前致谢

【问题讨论】:

    标签: c file structure


    【解决方案1】:

    fgets 用于从文本文件中以一行为单位输入字符串。

    例如)

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

    读入

    input_line_buff:(内容如) "name 66.6\n"

    您进行拆分、内存分配和复制以及转换。

    例如)

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

    【讨论】:

      【解决方案2】:

      试试这个,

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-06-11
        • 1970-01-01
        • 2013-12-11
        • 1970-01-01
        • 1970-01-01
        • 2023-03-06
        • 1970-01-01
        相关资源
        最近更新 更多