C++的文件内容删除操作

2025-03-22 12:48:15
推荐回答(1个)
回答1:

你的异常不是从你贴出的代码里来的,你贴出来的代码没什么问题。下面是我测试你代码的程序:(第一次运行的时候,将main中的生成Employee.dat的代码加上)
你注意比较一下。
#include
#include
using namespace std;

struct Department
{
char data;
long ID;
};

int Delete_worker(long id) //实现解雇功能
{
Department s1;

/*int id;
cout << "请输入你要删除的职工号码" << endl;
cin >> id;*/
fstream outfile("Employee_1.dat", ios::out | ios::in | ios::trunc | ios::binary);//创建一个临时文件
fstream infile("Employee.dat", ios::in|ios::binary);
if (!infile){ cout << "error" << endl; exit(0); }
if (!outfile){ cout << "error" << endl; exit(0); }
while (infile.read((char *)&s1, sizeof(s1)))
{

if (s1.ID == id)
continue;
else
{
outfile.write((char *)&s1, sizeof(s1));
}
}
outfile.close();
infile.close();
//接下来从临时文件往Employee.dat文件里更新后的内容
fstream file1("Employee_1.dat", ios::in | ios::binary);
fstream file2("Employee.dat", ios::out | ios::trunc);
if (!file1){ cout << "error" << endl; exit(0); }
if (!file2){ cout << "error" << endl; exit(0); }
while (file1.read((char *)&s1, sizeof(s1)))
{
file2.write((char *)&s1, sizeof(s1));
}
file1.close();
file2.close();
cout << "删除成功" << endl;
return 1;
}

void main()
{
int i;
/* Department d[10];
fstream of("Employee.dat", ios::out| ios::trunc|ios::binary);
for(i=0;i<10;i++)
{
d[i].ID=i;d[i].data=i+65;
of.write((char *)&d[i], sizeof(Department));
}
of.close();*/
Delete_worker(2);
}