C语言 删去一个职工的数据,再存回原文件。

 

将职一磁盘文件employee,内存放职工的数据。每个职工的数据包括职工姓名、职工 号、性别、年龄、住址、工资、健康状况、文化程度。今要求将职工名、工资的信息单独抽出来另建一个简明的职工工资文件。工名和工资的信息单独抽出来另建一个简明的职工工资文件。

#include <stdio.h>

typedef struct {
    char name[50];
    int id;
    char gender;
    int age;
    char address[100];
    float salary;
    char health[20];
    char education[20];
} Employee;

int main() {
    Employee emp;
    FILE *file = fopen("employee.txt", "r");
    FILE *salaryFile = fopen("salary.txt", "w");
    if (file == NULL || salaryFile == NULL) {
        printf("无法打开文件!\n");
        return 1;
    }

    while (fscanf(file, "%s %d %c %d %s %f %s %s", emp.name, &emp.id, &emp.gender, &emp.age, emp.address, &emp.salary, emp.health, emp.education) != EOF) {
        fprintf(salaryFile, "%s %.2f\n", emp.name, emp.salary);
    }

    fclose(file);
    fclose(salaryFile);
    printf("职工工资信息已保存到salary.txt文件中。\n");
    return 0;
}

将"职工工资文件"中删去一个职工的数据,再存回原文件。

#include <stdio.h>
#include <string.h>

int main() {
    char nameToDelete[50];
    char name[50];
    float salary;
    FILE *file = fopen("salary.txt", "r");
    FILE *tempFile = fopen("temp.txt", "w");
    if (file == NULL || tempFile == NULL) {
        printf("无法打开文件!\n");
        return 1;
    }

    printf("输入要删除的职工姓名:\n");
    scanf("%s", nameToDelete);

    while (fscanf(file, "%s %f", name, &salary) != EOF) {
        if (strcmp(name, nameToDelete) != 0) {
            fprintf(tempFile, "%s %.2f\n", name, salary);
        }
    }

    fclose(file);
    fclose(tempFile);

    remove("salary.txt");
    rename("temp.txt", "salary.txt");

    printf("职工数据已删除并更新到salary.txt文件中。\n");
    return 0;
}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值