含有文件操作的族谱c语言
时间: 2023-12-07 22:04:04 浏览: 60
以下是一个简单的包含文件操作的家谱树C语言代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 家族树节点
struct family_tree {
char name[20]; // 姓名
int age; // 年龄
struct family_tree *father; // 父亲指针
struct family_tree *child; // 孩子指针
};
// 从文件中读取家族树数据
void read_family_tree(struct family_tree **root) {
FILE *fp;
fp = fopen("family_tree.txt", "r");
if (fp == NULL) {
printf("无法打开文件 family_tree.txt!\n");
return;
}
// 从文件中读取数据并构建家族树
char line[50];
while (fgets(line, 50, fp)) {
char *name = strtok(line, ",");
int age = atoi(strtok(NULL, ","));
char *father_name = strtok(NULL, "\n");
// 查找父亲节点
struct family_tree *father = *root;
if (strcmp(father_name, "NULL") != 0) {
while (father) {
if (strcmp(father->name, father_name) == 0) {
break;
}
father = father->child;
}
} else {
father = NULL;
}
// 插入新节点
struct family_tree *new_node = (struct family_tree *) malloc(sizeof(struct family_tree));
strcpy(new_node->name, name);
new_node->age = age;
new_node->father = father;
new_node->child = NULL;
if (*root == NULL) {
*root = new_node;
} else {
struct family_tree *p = *root;
while (p->child) {
p = p->child;
}
p->child = new_node;
}
}
fclose(fp);
}
// 打印家族树
void print_family_tree(struct family_tree *root, int level) {
if (root == NULL) {
return;
}
for (int i = 0; i < level; i++) {
printf(" ");
}
printf("%s (%d)\n", root->name, root->age);
print_family_tree(root->child, level + 1);
}
int main() {
struct family_tree *root = NULL;
// 从文件中读取数据并构建家族树
read_family_tree(&root);
// 打印家族树
printf("家族树:\n");
print_family_tree(root, 0);
return 0;
}
```
在这个示例代码中,我们使用了文件操作函数来从文件中读取家族树数据。具体来说,我们使用了`fopen()`函数打开文件,使用`fgets()`函数逐行读取文件内容,并使用`strtok()`函数分割每行数据。然后,我们通过查找父亲节点和插入新节点来构建家族树。最后,我们使用递归函数打印整个家族树。
请注意,此示例代码仅用于演示文件操作和家族树的实现方式,实际应用时可能需要进行更多的错误处理和数据验证。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)