【C语言】:员工管系统开发指南(结构体数组+文件存储)丨完整源码+解析
代码针对Windows平台优化,使用安全的输入函数(scanf_s),适配VS编译器特性,并包含完整的数据持久化功能。
系统采用结构体数组存储数据,支持增删改查和文件存储。
#define _CRT_SECURE_NO_WARNINGS // 关闭VS安全警告
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
#define MAX_EMPLOYEES 1000 // 最大员工数
#define FILENAME "employees.dat" // 数据文件
// 员工信息结构体(内存对齐优化)
typedef struct {
int id; // 工号(主键)
char name[50]; // 姓名
char gender[6]; // 性别(固定长度减少内存碎片)
int age; // 年龄
char department[30]; // 部门
char position[30]; // 职位
char phone[16]; // 电话(+国际区号预留)
double salary; // 工资(双精度)
} Employee;
Employee employees[MAX_EMPLOYEES]; // 静态数组存储
int empCount = 0; // 当前员工数
// 函数声明
void loadData();
void saveData();
void addEmployee();
void displayAll();
void findEmployee();
void modifyEmployee();
void deleteEmployee();
void showMenu();
// 主函数(适配VS命令行窗口)
int main() {
system("chcp 65001"); // 设置控制台UTF-8编码
loadData(); // 启动加载数据
while (1) {
showMenu();
char choice = _getch(); // VS专用安全输入
switch (choice) {
case '1': addEmployee(); break;
case '2': displayAll(); break;
case '3': findEmployee(); break;
case '4': modifyEmployee(); break;
case '5': deleteEmployee(); break;
case '6': saveData(); break;
case '0':
saveData();
printf("\n数据已保存,系统退出!\n");
exit(0);
default:
printf("\n无效选项!\n");
_getch();
}
}
return 0;
}
// 从文件加载数据(二进制模式)
void loadData() {
FILE* file;
if (fopen_s(&file, FILENAME, "rb") != 0) { // VS安全文件打开
printf("\n数据文件不存在,将创建新文件\n");
return;
}
// 读取完整数组块
fread(&empCount, sizeof(int), 1, file);
fread(employees, sizeof(Employee), empCount, file);
fclose(file);
printf("\n已加载 %d 条记录\n", empCount);
}
// 保存数据到文件(含错误处理)
void saveData() {
FILE* file;
if (fopen_s(&file, FILENAME, "wb") != 0) {
printf("\n文件保存失败!\n");
return;
}
// 先写入记录数,再写数据块
fwrite(&empCount, sizeof(int), 1, file);
fwrite(employees, sizeof(Employee), empCount, file);
fclose(file);
printf("\n数据已保存(共%d条)\n", empCount);
}
// 添加员工(带输入验证)
void addEmployee() {
if (empCount >= MAX_EMPLOYEES) {
printf("\n员工数量已达上限!\n");
return;
}
Employee newEmp;
printf("\n--- 添加新员工 ---\n");
// 工号唯一性验证
int id, idExists;
do {
idExists = 0;
printf("工号: ");
scanf_s("%d", &id);
getchar(); // 清除输入缓冲区
for (int i = 0; i < empCount; i++) {
if (employees[i].id == id) {
printf("工号已存在!\n");
idExists = 1;
break;
}
}
} while (idExists);
newEmp.id = id;
printf("姓名: ");
scanf_s("%49s", newEmp.name, (unsigned)_countof(newEmp.name));
printf("性别(男/女): ");
scanf_s("%5s", newEmp.gender, (unsigned)_countof(newEmp.gender));
printf("年龄: ");
scanf_s("%d", &newEmp.age);
printf("部门: ");
scanf_s("%29s", newEmp.department, (unsigned)_countof(newEmp.department));
printf("职位: ");
scanf_s("%29s", newEmp.position, (unsigned)_countof(newEmp.position));
printf("电话: ");
scanf_s("%15s", newEmp.phone, (unsigned)_countof(newEmp.phone));
printf("工资: ");
scanf_s("%lf", &newEmp.salary);
employees[empCount++] = newEmp;