读书人

怎么修改和删除文件里的内容

发布时间: 2012-03-04 11:13:33 作者: rapoo

如何修改和删除文件里的内容
用文件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;

}

}


[解决办法]
文本覆盖、插入、修改,简单的示例一下:

#include <stdio.h>
#include <stdlib.h>

int main()
{
FILE *fp;
char *insert = "EE,EE,EE, ", tmp[256]={0};
int pos, i;

/*test.txt文件内容:01,00,00,00,0E,00,00,00,00,00,00,E1,E2,00,00,00,00*/
fp = fopen( "test.txt ", "r+ ");

/*1、等长覆盖*/
fseek(fp, 12, 1);
fprintf(fp, "0F "); /*直接写入等长度的数据就可以完成覆盖*/

/*2、E2后插入“EE,EE,EE,” */
fseek(fp, 25, 1);
pos = ftell(fp); /*插入位置*/
fgets(tmp, 256, fp); /*把后面的数据缓存*/
fseek(fp, pos, 0); /*移动到插入位置*/
fprintf(fp, insert); /*插入,就是写入数据*/
fprintf(fp, tmp); /*把原来的数据再写回来, 完成*/

/*3、01读取后++两次,并重新写回文件*/
rewind(fp);
fscanf(fp, "%x ", &i); /*读取数据*/
i = i+2; /* +2 */
fseek(fp, -2, 1); /*调整指针*/
fprintf(fp, "%02x ", i); /*写文件*/

fclose(fp);
system( "PAUSE ");
return 0;
}

读书人网 >C++

热点推荐