想要在文件中体现五个员工的信息,#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> typedef struct employee { char name[20]; char sex[5]; char salary[5]; }Employee; int main() { Employee emp[5] = { { "张三","F","1000"} ,{"李四","F","2000"},{"王五","M","3000"},{"赵六","M","4000"},{"孙七","F","5000"}}; FILE* fp; if ((fp = fopen("employee.dat", "w")) == NULL) { }else{ //printf("请入员工的信息\n"); //for (int i = 0; i < 5; i++) //{ // scanf("%s", emp[i].name); // scanf("%s", emp[i].sex); // scanf("%s", emp[i].salary); // // /*printf(emp[i].name, emp[i].sex, emp[i].salary);*/ // fputs(emp[i].name, fp); // fputs(emp[i].sex, fp); // fputs(emp[i].salary, fp); //} Employee* pw=emp; for (int i = 0; i < 5; i++) { Employee* pw=&emp[i]; fwrite(emp, sizeof(emp[5]), 1, fp); //写入文件student.dat pw++; } Employee* pr = emp; for (int j = 0; j < 5; j++) { fread(emp, sizeof(emp[5]), 1, fp); pr++; } } fclose(fp); system("pause"); }
时间: 2024-03-02 12:52:22 浏览: 101
如果您想要在文件中体现五个员工的信息,可以将员工信息写成文本格式,比如用逗号分隔各个属性,每个员工信息占一行,示例代码如下:
```c
#include<stdio.h>
#include<stdlib.h>
typedef struct employee {
char name[20];
char sex[5];
char salary[5];
} Employee;
int main() {
Employee emp[5] = {{"张三","F","1000"}, {"李四","F","2000"}, {"王五","M","3000"}, {"赵六","M","4000"}, {"孙七","F","5000"}};
FILE* fp;
if ((fp = fopen("employee.txt", "w")) == NULL) {
printf("文件打开失败\n");
exit(1);
}
for (int i = 0; i < 5; i++) {
fprintf(fp, "%s,%s,%s\n", emp[i].name, emp[i].sex, emp[i].salary);
}
fclose(fp);
if ((fp = fopen("employee.txt", "r")) == NULL) {
printf("文件打开失败\n");
exit(1);
}
char buf[100];
while (fgets(buf, 100, fp) != NULL) {
printf("%s", buf);
}
fclose(fp);
return 0;
}
```
这里将员工信息写到"employee.txt"文件中,每行一个员工信息,每个属性之间用逗号隔开。在读取文件时,使用fgets函数按行读取文件内容,再输出到屏幕上。
阅读全文