返回:贺老师课程教学链接
【项目4 - 间隔选职工】
(1)从键盘输入10名职工的工号、姓名和年龄,并保存到二进制文件worker.rec中
用下面的结构体表示一名职工的记录
typedef struct
{
int num; //工号
char name[10]; //姓名
int age; //年龄
} Worker;
[参考解答]
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int num; //工号
char name[10]; //姓名
int age; //年龄
} Worker;
int main( )
{
int i;
FILE *fp;
if ((fp=fopen("worker.rec","wb"))==NULL)
{
printf("connot open\n");
exit(1);
}
Worker worker;
for (i=0; i<10; i++)
{
scanf("%d %s %d", &worker.num, worker.name, &worker.age);
fwrite(&worker, sizeof(Worker),1, fp);
}
fclose(fp);
return 0;
}
(2)从文件中读取并显示顺序号为奇数的职工记录。(即第 1,3,5,…号职工的数据)
[参考解答]
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int num; //工号
char name[10]; //姓名
int age; //年龄
} Worker;
int main( )
{
int i;
FILE *fp;
if ((fp=fopen("worker.rec","rb"))==NULL)
{
printf("connot open\n");
exit(1);
}
Worker worker;
for (i=0; i<10; i+=2)
{
fseek(fp,i*sizeof(Worker),SEEK_SET);
fread(&worker, sizeof(Worker),1, fp);
printf("%d\t%s\t%d\n", worker.num, worker.name, worker.age);
}
fclose(fp);
return 0;
}
时间: 2024-09-20 23:35:40