如何将文件中的数据读取到结构体中? 我有一个像
的结构struct data
{
char name[20];
int age;
};
在文件student_info.txt
中我有
ravi 12 raghu 14 datta 13 sujay 10 rajesh 13
等等,还有许多其他有年龄的名字。如何将其从文件读取到结构数据?
读取这个名字和年龄应该是一个循环,即第一次我将读取“ravi”和“12”,然后我应该将这些数据打包到结构中,并在结构完成后立即将结构传递给函数已设置。它应该返回到文件并再次读取“raghu”和“14”,并用这些数据打包结构,并且这应该处于循环状态,直到我从文件中读取所有数据
谁能告诉我如何实现这个逻辑吗?
最佳答案
方法是:
- 创建结构体数组的实例、用于文件访问的文件指针和计数器变量
- 使用文件指针打开文件流 - 检查是否已成功打开。如果 fopen() 失败,文件指针将指向 NULL
- 使用循环将数据读入结构体数组。 fscanf() 返回与其格式字符串成功“匹配”的数量 - 此处为 2(将其用于循环条件)
- 关闭文件
代码示例:
#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;
}
关于c - 从文件中读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6327097/