怎么删除和修改文件里的内容
如何删除和修改文件里的内容
用文件data.dat保存一个结构数组stu[3],
再读取文件内容,把文件内容拷贝到结构数组copy[3],
如果要修改data文件里的内容,应该怎么修改 谢谢
具体程序如下(只有写文件的部分)
#include <iostream.h>
#include <fstream.h>
#include <string.h>
struct student
{
char name[20];
char num[10];
int score;
};
void main()
{
student stu[3]={{ "nihao ", "1541 ",90},{ "gsdhao ", "1542 ",93},{ "nfado ", "1543 ",95}};
student s;
student copy[3];
fstream f1;
f1.open( "data.dat ",ios::out|ios::in|ios::binary);
if(!f1)
{
cout < < "no open " < <endl;
return;
}
for(int i=0; i <3;i++)
{f1.write((char*)&stu[i],sizeof(student));}
for(int n=0; n <3;n++)
{
f1.seekp(sizeof(student)*n);
f1.read((char*)&s,sizeof(student));
strcpy(copy[n].name,s.name);
strcpy(copy[n].num,s.num);
copy[n].score=s.score;
cout < <copy[n].name < < "------------ " < <copy[n].num < < "---------- " < <copy[n].score < <endl;
}
}
------解决方案--------------------
把需要的内容写到buffer中,清空原来的文件,然后把需要的内容写回去,这样就达到了修改原来文件的目的,或者通过写到另一个文件而将原文件删除来达到目的,似乎目前的操作系统仅提供了这种方法,而没有提供更直接的方法....
------解决方案--------------------
你程序中f1.seekp(sizeof(student)*n);是不必要的,因为读后指针会自动移动的。
要修改文件里的数据可以用seekp函数移动到确切的位置,直接写入覆盖掉原来的数据
用文件data.dat保存一个结构数组stu[3],
再读取文件内容,把文件内容拷贝到结构数组copy[3],
如果要修改data文件里的内容,应该怎么修改 谢谢
具体程序如下(只有写文件的部分)
#include <iostream.h>
#include <fstream.h>
#include <string.h>
struct student
{
char name[20];
char num[10];
int score;
};
void main()
{
student stu[3]={{ "nihao ", "1541 ",90},{ "gsdhao ", "1542 ",93},{ "nfado ", "1543 ",95}};
student s;
student copy[3];
fstream f1;
f1.open( "data.dat ",ios::out|ios::in|ios::binary);
if(!f1)
{
cout < < "no open " < <endl;
return;
}
for(int i=0; i <3;i++)
{f1.write((char*)&stu[i],sizeof(student));}
for(int n=0; n <3;n++)
{
f1.seekp(sizeof(student)*n);
f1.read((char*)&s,sizeof(student));
strcpy(copy[n].name,s.name);
strcpy(copy[n].num,s.num);
copy[n].score=s.score;
cout < <copy[n].name < < "------------ " < <copy[n].num < < "---------- " < <copy[n].score < <endl;
}
}
------解决方案--------------------
把需要的内容写到buffer中,清空原来的文件,然后把需要的内容写回去,这样就达到了修改原来文件的目的,或者通过写到另一个文件而将原文件删除来达到目的,似乎目前的操作系统仅提供了这种方法,而没有提供更直接的方法....
------解决方案--------------------
你程序中f1.seekp(sizeof(student)*n);是不必要的,因为读后指针会自动移动的。
要修改文件里的数据可以用seekp函数移动到确切的位置,直接写入覆盖掉原来的数据