将txt的数据写入结构体
时间: 2023-09-30 17:05:05 浏览: 38
假设txt文件中的数据格式为:
```
John,Doe,30
Jane,Smith,25
Bob,Johnson,40
```
可以定义一个结构体来保存这些数据,如下所示:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_LEN 50
typedef struct {
char first_name[MAX_LEN];
char last_name[MAX_LEN];
int age;
} Person;
int main() {
FILE *file = fopen("data.txt", "r");
if (file == NULL) {
printf("Failed to open file\n");
return 1;
}
Person people[100];
int i = 0;
while (fscanf(file, "%s,%s,%d", people[i].first_name, people[i].last_name, &people[i].age) == 3) {
i++;
}
int num_people = i;
fclose(file);
// Print out the data
for (i = 0; i < num_people; i++) {
printf("%s %s, %d\n", people[i].first_name, people[i].last_name, people[i].age);
}
return 0;
}
```
上述代码中,我们定义了一个Person结构体来表示每个人的信息。在主函数中,我们使用fopen函数打开txt文件,并使用fscanf函数逐行读取数据并将其存储在people数组中。最后,我们打印出所有人的信息。