MST

星途 面试题库

面试题:C语言fscanf和fprintf处理复杂格式数据

给定一个文本文件,其中记录了一系列员工的信息,格式为:员工ID(8位数字),员工姓名(长度不定),部门(长度不定),薪资(浮点数),各信息之间用逗号分隔,每行一个员工信息。要求使用fscanf读取文件内容,对薪资进行一定的调整(例如增加10%),然后使用fprintf将调整后的员工信息写回到原文件覆盖原有内容。请编写代码实现,注意处理文件操作可能出现的错误。
32.3万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试
#include <stdio.h>
#include <stdlib.h>

int main() {
    FILE *file = fopen("employees.txt", "r+");
    if (file == NULL) {
        perror("Failed to open file");
        return 1;
    }

    int id;
    char name[100];
    char department[100];
    double salary;

    // 临时文件用于存储修改后的内容
    FILE *tempFile = fopen("temp.txt", "w");
    if (tempFile == NULL) {
        perror("Failed to create temp file");
        fclose(file);
        return 1;
    }

    while (fscanf(file, "%d,%99[^,],%99[^,],%lf\n", &id, name, department, &salary) == 4) {
        salary *= 1.1; // 增加10%
        fprintf(tempFile, "%08d,%s,%s,%.2lf\n", id, name, department, salary);
    }

    fclose(file);
    fclose(tempFile);

    // 删除原文件
    if (remove("employees.txt") != 0) {
        perror("Failed to remove original file");
        return 1;
    }

    // 重命名临时文件为原文件名
    if (rename("temp.txt", "employees.txt") != 0) {
        perror("Failed to rename temp file");
        return 1;
    }

    return 0;
}