编写c语言程序:定义员工结构体(员工信息有员工号,员工姓名,部门)。定义一个结构体变量,并使用结构体指针变量对结构体变量赋值,并写入到文件C:\employer.txt文件中。 2.在程序1的基础上,编写函数模块从C:\employer.txt中读取数据并打印输出到屏幕上。
时间: 2023-05-17 14:07:31 浏览: 145
下面程序是定义一个结构体,并为其定义结构体变量,对其值输入、输出。
5星 · 资源好评率100%
答案:
1. 以下是编写的C语言程序:
```
#include <stdio.h>
#include <stdlib.h>
struct Employee {
int empNo;
char empName[50];
char department[50];
};
int main() {
struct Employee emp;
struct Employee *empPtr = &emp;
printf("Enter employee number: ");
scanf("%d", &emp.empNo);
printf("Enter employee name: ");
scanf("%s", emp.empName);
printf("Enter department: ");
scanf("%s", emp.department);
FILE *fp;
fp = fopen("C:\\employer.txt", "w");
if (fp == NULL) {
printf("Error opening file\n");
exit(1);
}
fprintf(fp, "%d %s %s\n", empPtr->empNo, empPtr->empName, empPtr->department);
fclose(fp);
printf("Employee details written to file successfully.\n");
return 0;
}
```
2. 以下是从C:\employer.txt中读取数据并打印输出到屏幕上的函数模块:
```
#include <stdio.h>
#include <stdlib.h>
struct Employee {
int empNo;
char empName[50];
char department[50];
};
void printEmployeeDetails() {
struct Employee emp;
struct Employee *empPtr = &emp;
FILE *fp;
fp = fopen("C:\\employer.txt", "r");
if (fp == NULL) {
printf("Error opening file\n");
exit(1);
}
fscanf(fp, "%d %s %s", &empPtr->empNo, empPtr->empName, empPtr->department);
printf("Employee Number: %d\n", empPtr->empNo);
printf("Employee Name: %s\n", empPtr->empName);
printf("Department: %s\n", empPtr->department);
fclose(fp);
}
int main() {
printEmployeeDetails();
return 0;
}
```
阅读全文