C语言如何将txt内容存入结构体
时间: 2024-11-11 16:06:44 浏览: 73
在C语言中,你可以使用文件操作函数来读取.txt文件的内容,并将其存储到自定义的结构体中。这里是一个简单的例子,假设你有一个名为`Student`的结构体,用于存储学生的姓名和年龄:
```c
#include <stdio.h>
#include <stdlib.h> // 包含字符串处理函数
#define MAX_NAME_LENGTH 50
typedef struct {
char name[MAX_NAME_LENGTH];
int age;
} Student;
// 功能:从文本文件读取数据并填充结构体
void read_from_txt(char *filename, Student *students) {
FILE *file = fopen(filename, "r"); // 打开文件
if (file == NULL) {
perror("Error opening file");
return;
}
while (!feof(file)) { // 遍历文件直到结束
fgets(students->name, MAX_NAME_LENGTH, file); // 读取名字
students->age = fscanf(file, "%d", &students->age); // 读取年龄
students++; // 进入下一个结构体元素
}
fclose(file); // 关闭文件
}
int main() {
const int num_students = 5; // 假设你要读取5名学生
Student students[num_students];
// 调用函数读取.txt文件
read_from_txt("students.txt", students);
// 现在学生们的信息已存储在结构体数组中
for (int i = 0; i < num_students; i++) {
printf("Name: %s, Age: %d\n", students[i].name, students[i].age);
}
return 0;
}
阅读全文
相关推荐
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)