要求:
1、 定义结构体employee
2、 定义结构体数组emps
3、 利用fwirte把数组中的值写入到employee.dat中
4、 利用fread把employee.dat的内容读出来显示
#include <QCoreApplication>
#include <iostream>
#include <fstream>
using namespace std;
struct Employee{
int num;
char name[20];
};
int addInFile(Employee * emps, int num)
{
ofstream outFile("employee.dat",ios::out|ios::binary); //定义文件输出流 文件不存在时创建文件
//对文件打开错误时的操作
if(!outFile)
{
cout<<"The file open error!"<<endl;
return 0;
}
else //文件正常打开时,进行相应的处理
{
for(int i = 0; i < num; i++)
{
Employee * pemp = emps + i;
outFile.write((char*)pemp,sizeof(Employee)); //文件输出流向文件中写入employee信息
}
}
outFile.close(); //关闭输出流
return 1;
}
int myReadFile(Employee * emps, int num)
{
ifstream inFile("employee.dat",ios::in|ios::binary); //文件输入流 将文件中的employee信息读出到屏幕上
//对文件打开错误时的操作
if(!inFile)
{
cout<<"The inFile open error!"<<endl;
return 0;
}
else
{
Employee *emp = emps;
for (int i = 0; i < num; i++, emp++)
{
inFile.read((char*)emp,sizeof(Employee));
}
}
inFile.close(); //关闭输入流
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
cout<<"start"<<endl;
Employee emps[10];
Employee readedEmps[10];
memset(readedEmps, 0,sizeof(readedEmps));
for(int i = 0; i < 10; i++)
{
emps[i].num = i;
sprintf(emps[i].name,"tom_%d",i);
}
addInFile(emps, 10); //添加结构体
myReadFile(readedEmps, 10); //读取结构体
for(int i = 0; i < 10; i++){
cout<<"Employee "<<readedEmps[i].num<<": "<<readedEmps[i].name<<endl;
}
return a.exec();
}
C语言代码如下:
#define N 5
#include <stdio.h>
struct Employee
{char name[15];
char addr[20];
char city[15];
int code;
} doc[N];
void set()
{ int i,j;
for (i=0;i<N;i++)
{printf("\n Please input %d of %d\n",i+1,N);
printf("Name:");
scanf("%s",doc[i].name);
printf("Addr:");
scanf("%s",doc[i].addr);
printf("City:");
scanf("%s",doc[i].city);
printf("Code:");
scanf("%d",&doc[i].code);
}
printf("\n");
}
void disp()
{int i;
printf("\nName\t\tAddr\t\tCity\t\tCode\n");
for (i=0;i<N;i++)
{printf("%s\t\t%s\t\t%s\t\t%d",doc[i].name,doc[i].addr,doc[i].city,doc[i].code);
printf("\n");
}
}
//主程序很简单,调用set函数给结构体赋值,调用disp函数输出录入信息。
int main()
{
set();
disp();
return 0;
}