IO进程day1

思维导图

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// 定义学生结构体  
typedef struct Student {  
    char name;  
    int age;  
    float score;  
    struct Student *next;  
} Student;  
  
// 创建新节点  
Student* createStudent( char* name, int age, float score)
{  
    Student* H = (Student*)malloc(sizeof(Student));  
    if(H == NULL) 
	{  
        perror("错误\n");  
        return NULL;  
    }  
    strcpy(H->name, name);  
    H->age = age;  
    H->score = score;  
    H->next = NULL;  
    return H;  
}  
// 向链表添加学生  
void addStudent(Student* head, char* name, int age, float score) {  
    Student* newStudent = createStudent(name, age, score);  
    if () {  
        *head = newStudent;  
    } else {  
        Student* current = *head;  
        while (current->next) {  
            current = current->next;  
        }  
        current->next = newStudent;  
    }  
}   
// 保存链表到文件  
void save( Student* head, char* filename)
{  
    FILE* wfp = fopen(filename, "w");  
    if (wfp == NULL)
	{  
        printf("错误\n");  
        return 1;  
    }  
     Student* current = head;  
    while (current) {  
        fprintf(file, "%s,%d,%f\n", current->name, current->age, current->score);  
        current = current->next;  
    }  
    fclose(file);  
}  
// 从文件加载学生到链表  
void load(Student* head,  char* filename) {  
    FILE* file = fopen(filename, "r");  
    if (file == NULL) {  
        printf("错误\n");  
        return ;  
    }  
    char name;  
    int age;  
    float score;  
    while (fscanf(file, "%[^,],%d,%f\n", name, &age, &score) != EOF) {  
        addStudent(head, name, age, score);  
    }  
    fclose(file);  
}  
// 显示链表内容  
void display(const Student* head) {  
    const Student* current = head;  
    while (current) {  
        printf("Name: %s, Age: %d, Score: %.2f\n", current->name, current->age, current->score);  
        current = current->next;  
    }  
}  
// 释放链表内存  
void freeStudents(Student* head) {  
    Student* current = head;  
    while (current) {  
        Student* next = current->next;  
        free(current);  
        current = next;  
    }  
}  
int main()
{  
    Student* head = NULL;   
    addStudent(&head, "张三", 20, 85.5);  
    addStudent(&head, "李四", 21, 92.0);  
    addStudent(&head, "王五", 19, 78.0);  
 
    return 0;  
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值