以下代码是为了解决“在二进制文件student.dat中写入三条记录,显示其内容,然后删除第二条记录,显示删除记录后的文件内容。”这个问题。
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
int i=0,j=0;
char a[100],b[100],c[100],d[100];
cout<<"请输入三条记录(每条记录以#结束):\n"
<<"第一条:\n";
cin.getline(a,100,'#');
cout<<"第二条:\n";
cin.getline(b,100,'#');
cout<<"第三条:\n";
cin.getline(c,100,'#');
//导入数据
ofstream outfile("student.dat");
ofstream fcout("d:\\student1.dat",ios::binary);
if(fcout.fail())
{
cerr<<"error opening file\n";
return 0;
}
fcout<<a<<endl<<b<<endl<<c<<endl;
fcout.close();
fcout.clear();
//读取输出
ifstream fcin("d:\\student.dat",ios::binary);
if(fcin.fail())
{
cerr<<"error opening file\n";
return 0;
}
fcin.getline(d,100,'#');
cout<<"删除前为:\n";
cout<<d<<endl;
//删除
while(a[i]!='\0')
{
d[i]=a[i];
i++;
}
while(c[j]!='\0')
{
d[i]=c[j];
i++,j++;
}
d[i]='\0';
cout<<"删除后为:\n"
<<d<<endl;
fcin.close();
//重新写入
ofstream fcout1("d:\\student.dat",ios::trunc);
if(fcout1.fail())
{
cerr<<"error opening fail!\n";
return 0;
}
for(j=0;j<i;j++)
fcout1<<d[j]<<endl;
fcout1.close();
return 0;
}
注意点:
1、ofstream是一个类,fcout是这个类的对象(fcout的名字可以任意取,但最好取得好认一点)。“cout”针对的是基本数据类型,所以要专门定义一个“fcout”来对文件进行操作,且“fcout”的操作与“cout”操作基本相同。
2、要用fcout.fail()来判断文件是否打开,若文件正确打开,则返回值为“fault”,否则为“true”。
3、“fcin>>d”的含义是指将文件流中的与“d”的数据类型相同的数据读到“d”中,用“fcin>>d”只能读取没有空格的字符串,用“fcin.getline(d,100,‘#’)”才可读取有空格的字符串。
4、在对文件操作结束后,要用“f.close()”关闭文件,若想在一个程序中多次打开用一个文件,就要用“f.clear()”。
5、删除数据,可以将数据放在数组中,用后面的数据覆盖掉需要删除的数据。(我能想到的只有这个,若有更好的方法,请多多指点,谢谢。)。
6、用ios::trunc模式打开文件可以重写文件。