下面是修改后的代码:

#include <stdio.h>
#include <stdlib.h>

struct student {
    int id;
    char name[10];
    int score;
};

struct node {
    struct student data;
    struct node *next;
};

void inputDatafromFile(struct node **head) {
    FILE *fp;
    fp = fopen('data.txt', 'r');
    if (fp == NULL) {
        printf('File open error!\n');
        return;
    }
    struct node *p, *tail;
    tail = *head;
    while (!feof(fp)) {
        p = (struct node*)malloc(sizeof(struct node));
        if (p == NULL) {
            printf('Memory allocation failed!\n');
            return;
        }
        fscanf(fp, '%d%s%d', &p->data.id, p->data.name, &p->data.score);
        if (*head == NULL) {
            *head = p;
        } else {
            tail->next = p;
        }
        tail = p;
    }
    tail->next = NULL;
    fclose(fp);
}

void outputDatatoFile(struct node *head) {
    FILE *fp;
    fp = fopen('data.txt', 'w');
    if (fp == NULL) {
        printf('File open error!\n');
        return;
    }
    struct node *p;
    p = head;
    while (p != NULL) {
        fprintf(fp, '%d %s %d\n', p->data.id, p->data.name, p->data.score);
        p = p->next;
    }
    fclose(fp);
}

void insert(struct node **head, struct student stu) {
    struct node *p, *q;
    p = (struct node*)malloc(sizeof(struct node));
    if (p == NULL) {
        printf('Memory allocation failed!\n');
        return;
    }
    p->data = stu;
    if (*head == NULL) {
        *head = p;
        p->next = NULL;
    } else {
        q = *head;
        if (p->data.id < q->data.id) {
            p->next = q;
            *head = p;
        } else {
            while (q->next != NULL && p->data.id > q->next->data.id) {
                q = q->next;
            }
            p->next = q->next;
            q->next = p;
        }
    }
    outputDatatoFile(*head); // 在插入学生记录函数中增加调用数据存盘函数
}

void print(struct node *head) {
    struct node *p;
    p = head;
    while (p != NULL) {
        printf('%d %s %d\n', p->data.id, p->data.name, p->data.score);
        p = p->next;
    }
}

int main() {
    struct node *head = NULL;
    inputDatafromFile(&head); // 在 main()前端调用读入学生记录函数
    struct student stu1 = {1, 'Tom', 80};
    struct student stu2 = {3, 'Jerry', 90};
    insert(&head, stu1);
    insert(&head, stu2);
    print(head);
    return 0;
}

原文地址: https://www.cveoy.top/t/topic/oUxk 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录