从文件中读取数据

时间:2011-06-13 05:57:15

标签: c structure

如何将文件中的数据读取到结构中? 我有一个像

这样的结构
struct data
{
    char name[20];
    int age;
};

在档案student_info.txt我有

   ravi 12 raghu 14 datta 13 sujay 10 rajesh 13

以及许多其他年龄段的名字。如何从文件中读取结构数据?

读取这个名字和年龄应该是一个循环,即我第一次阅读'ravi'和'12',然后我应该将这些数据打包到结构中,并且一旦结构将结构传递给函数已设定。它应该回到文件并读取'raghu'和'14'再次打包带有这些数据的结构,这应该是一个循环,直到我读取文件中的所有数据

有人可以告诉我们如何实现逻辑吗?

2 个答案:

答案 0 :(得分:1)

方法是:

  1. 创建结构数组的实例,文件访问的文件指针和计数器变量
  2. 使用文件指针打开文件流 - 检查它是否已成功打开。如果fopen()失败,文件指针将指向NULL
  3. 使用循环将数据读入struct数组。 fscanf()返回成功'匹配'的数量及其格式字符串 - 这里它将是2(用于循环条件)
  4. 关闭文件
  5. 代码示例:

    #include <stdio.h>
    
    #define FILENAME "student_info.txt"
    #define MAX_NO_RECORDS 50
    
    struct data
    {
    char name[20];
    int age;
    };
    
    int main(void)
    {
        /* Declare an array of structs to hold information */
        struct data StudentInfo[MAX_NO_RECORDS];
        /* Declare a file pointer to access file */
        FILE *s_info;
        int student_no = 0; /* holds no. of student records loaded */
    
        /* open the file for reading */
        s_info = fopen(FILENAME, "r");
        /* Check if an error has occured - exit if so */
        if(s_info == NULL)
        {
            printf("File %s could not be found or opened - Exiting...\n", FILENAME);
            return -1;
        }
    
        printf("Loading data...\n");
        while(fscanf(s_info, "%19s %i", StudentInfo[student_no].name, &StudentInfo[student_no].age) == 2)
        {
            /* refer to records with index no. (0 to (1 - no. of records))
                individual members of structure can be accessed with . operator */
            printf("%i\t%-19s %3i\n", student_no, StudentInfo[student_no].name, StudentInfo[student_no].age);
            student_no++;
        }
        /* after the loop, student_no holds no of records */
        printf("Total no. of records = %i\n", student_no);
        /* Close the file stream after you've finished with it */
        fclose(s_info);
    
        return 0;
    }
    

答案 1 :(得分:0)

您只需要从此文件中读取数据并根据某些条件拆分该字符串。由于您的文件格式不正确,因此您很难解析数据。

在当前场景中,您的文件只包含名字和数字,您可以通过检测字符串中的空格字符轻松解析此数字。但如果您的任何名字包含空格,这可能会导致问题。

首先,通过某些字符分隔每对单词,例如:或;或制表符或换行符。 然后在每个分隔的字符串之间按空格分割,然后读取char数组中的所有文件内容,然后从该数组中尝试找到表示一条记录的特殊字符。 将每个记录分隔在不同的char数组中,然后再次为每个生成的数组分离,然后根据空间char并在结构中加载来分割它

这只是为了解释,原始实现可能会有所不同,

Student std = {first string, second integer};

希望该文档能够解决您的问题http://www.softwareprojects.com/resources//t-1636goto.html