文件流读写完整案例
下面是一个关于文件流读写入的实际示例
首先,我们定义了Employee的类,关于这个类我们的api原型我们会放到employee.hh文件,代码的主体实现放在emloyee.cpp文件中.
- employee.hh文件
//employee.hhw文件
//作者:铁甲万能🐶
//授权方式:谢绝转载
#include <iostream>
using namespace std;
class Employee {
int eid;
char name[25];
char depart[5];
float salary;
char grade;
public:
void getdata() {
cout << "--职员信息录入--" << endl;
cout << "工号:";
cin >> eid;
cout << "姓名:";
cin >> name;
cout << "部门:";
cin >> depart;
cout << "薪水:";
cin >> salary;
cout << "绩效:(分级有 'A', 'B', 'C', 'D'):";
cin >> grade;
evaluate();
}
void evaluate();
void display();
void update();
int getID() { return eid; }
};
- employee.cpp文件
#include "../header/employee.hh"
void Employee::evaluate() {
if (grade == 'A') {
salary = salary * 1.10;
} else if (grade == 'B') {
salary = salary * 1.07;
} else if (grade == 'C') {
salary = salary * 1.04;
} else {
salary = salary * 0.95;
}
}
void Employee::display() {
cout << "----员工信息-----" << endl;
cout << "工号:" << eid << endl;
cout << "姓名:" << name << endl;
cout << "薪水:" << salary << endl;
cout << "评级:" << grade << endl;
}
void Employee::update() {}
当然还少不掉我们的调用层代码
#include <fstream>
#include <iostream>
#include "./utils/tool.cpp"
#include "employee.cpp"
/**https://github.com/courri/Cpp-Primer-5th-Edition/blob/master/7/useScreen.cpp**/
using namespace std;
int main(int argc, char const *argv[]) {
string filename("../files/emp.db");
fstream dbf;
if (!exists(filename)) {
dbf.open(filename, ios::out);
dbf.close();
}
dbf.open(filename, ios::in | ios::app | ios::binary);
char answer = 'y';
cout << "需要录入职员数据吗?" << endl;
cin >> answer;
Employee emp = Employee();
//写操作
while (true) {
emp.getdata();
dbf.write((char *)&emp, sizeof(emp));
cout << "记录大小:" << sizeof(emp) << "字节" << endl;
cout << "添加职工记录到emp.db" << endl;
cout << "还需要继续吗?" << endl;
cin >> answer;
if (answer != 'y' && answer != 'Y') {
break;
}
}
if (!dbf.is_open()) {
cout << "加载dbf文件" << endl;
dbf.open(filename, ios::in | ios::binary);
}
dbf.seekg(0);
while (!dbf.eof()) {
dbf.read((char *)&emp, sizeof(emp));
emp.display();
}
return 0;
}
插入新数据
那么我们看看我们保存到emp.db文件的二进制数据信息,这里我们需要可以打开二进制的文本工具,这里推荐wxhexeditor.
ubuntu下安装如下:
sudo apt-get install wxhexeditor
我们可以发现已经写入相关的信息了,下图涉及到C/C++内存管理和对象数据序列化的话题,我们会在日后的文章另行展开话题
2019-08-31 16-34-51 的螢幕擷圖.png
网友评论