最近在写进程调度实验,遇到自定义结构体多次写入和读取,网上搜了很久都没有相关帖子。
最后再b站的“码农论坛”Up那里学会了。
在这和大家分享一下。
#include <fstream>
struct PCB //自定义pcb类型结构体
{
char name;
int state=0;//状态
int ctime=2;//所需时间
};
void writepcb(linkq q)//写一个实现写操作的函数
{
ofstream ofs;
ofs.open("test.txt", ios::out || ios::binary);
if (ofs.is_open() == false) { cout << "文件打开失败!"; }
PCB pcb;//声明结构体
//写法一
pcb = { 'a',1,2};
ofs.write((const char*)&pcb, sizeof(PCB));
pcb = { 'b',1,3};
ofs.write((const char*)&pcb, sizeof(PCB));
pcb = { 'c',1,2};
ofs.write((const char*)&pcb, sizeof(PCB));
//写法二
int select = 1;
cout << "是否继续添加进程:添加(1)/否(0)" << endl;
cin >> select;
while (select) {
cin >> pcb.name;
cin >> pcb.state;
cin >> pcb.ctime;
ofs.write((const char*)&pcb, sizeof(PCB));
cout << "添加进程成功!是否继续添加:添加(1)/否(0)" << endl;
cin >> select;
}
ofs.close();
}
void readpcb()//写实现一个读文件的函数
{
cout << "成功读取文件!" << endl;
ifstream ifs("test.txt", ios::in || ios::binary);
if (!ifs.is_open())
{
cout << "文件打开失败" << endl;
}
struct PCB {
char name;
int state = 0;//状态
int ctime = 2;//所需时间
}pcb;//声明结构体类型
while (ifs.read((char*)&pcb, sizeof(pcb)))
{
cout << "进程名:" << pcb.name;
if (pcb.state == 1)
{
cout << "就绪态\t";
}
else { cout << "阻塞态\t"; }
cout << "要求服务时间:\t" << pcb.ctime;
cout << endl;
}
ifs.close();
}
so,就酱,如果还有其他问题可以评论区聊聊,最好也去看看那个Up的视频讲的挺好的。