当然可以,以下是que_remv_modi.c的代码:

#include <stdio.h> #include <stdlib.h> #include <string.h> #include "student.h"

void query() { char name[20]; printf("请输入要查询的学生姓名:"); scanf("%s", name);

FILE* fp = fopen("student.dat", "rb");
if (fp == NULL) {
    printf("文件打开失败!\n");
    return;
}

Student stu;
int found = 0;
while (fread(&stu, sizeof(Student), 1, fp) == 1) {
    if (strcmp(stu.name, name) == 0) {
        printf("学号:%d\n姓名:%s\n性别:%s\n成绩:%d\n", stu.id, stu.name, stu.gender, stu.score);
        found = 1;
        break;
    }
}

if (!found) {
    printf("未找到该学生!\n");
}

fclose(fp);

}

void remove_student() { char name[20]; printf("请输入要删除的学生姓名:"); scanf("%s", name);

FILE* fp = fopen("student.dat", "rb");
if (fp == NULL) {
    printf("文件打开失败!\n");
    return;
}

FILE* tmp = fopen("tmp.dat", "wb");
if (tmp == NULL) {
    printf("临时文件打开失败!\n");
    fclose(fp);
    return;
}

Student stu;
int found = 0;
while (fread(&stu, sizeof(Student), 1, fp) == 1) {
    if (strcmp(stu.name, name) == 0) {
        found = 1;
    } else {
        fwrite(&stu, sizeof(Student), 1, tmp);
    }
}

fclose(fp);
fclose(tmp);

if (!found) {
    printf("未找到该学生!\n");
    remove("tmp.dat");
} else {
    remove("student.dat");
    rename("tmp.dat", "student.dat");
    printf("删除成功!\n");
}

}

void modify() { char name[20]; printf("请输入要修改的学生姓名:"); scanf("%s", name);

FILE* fp = fopen("student.dat", "rb+");
if (fp == NULL) {
    printf("文件打开失败!\n");
    return;
}

Student stu;
int found = 0;
while (fread(&stu, sizeof(Student), 1, fp) == 1) {
    if (strcmp(stu.name, name) == 0) {
        printf("请输入学生新信息:\n");
        printf("学号:");
        scanf("%d", &stu.id);
        printf("姓名:");
        scanf("%s", stu.name);
        printf("性别:");
        scanf("%s", stu.gender);
        printf("成绩:");
        scanf("%d", &stu.score);
        fseek(fp, -sizeof(Student), SEEK_CUR);
        fwrite(&stu, sizeof(Student), 1, fp);
        found = 1;
        break;
    }
}

if (!found) {
    printf("未找到该学生!\n");
} else {
    printf("修改成功!\n");
}

fclose(fp);

}


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

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