关于文件操作的问题!急!

feiyinggood 2003-07-18 11:22:13
假设我手头上有一个TXT文件a.txt内容如下:
abcdefghijklmnopqrstuvwxyz
现在我需要在abc的后面插入xyz使a.txt的内容变成:
abcxyzdefghijklmnopqrstuvwxyz
我已经想到了一种办法,代码如下:
int iFileHandle=FileOpen("c:\\a.txt",fmOpenReadWrite);
int iFileLength=FileSeek(iFileHandle,0,2);
FileSeek(iFileHandle,0,0);
char *pszBuffer=new char[iFileLength+1];
FileRead(iFileHandle, pszBuffer, iFileLength);
pszBuffer[iFileLength]='\0';
AnsiString as1=pszBuffer;
delete [] pszBuffer;
as1=as1.SubString(1,3)+"xyz"+as1.SubString(4,iFileLength);
pszBuffer=new char[as1.Length()+1];
pszBuffer=as1.c_str();
FileSeek(iFileHandle,0,0);
FileWrite(iFileHandle,pszBuffer,iFileLength+3);
FileClose(iFileHandle);
但是,这种办法对大容量的TXT文件(大概10MB)不行,请问大哥有没有其他插入的办法,而且可以推广到对大容量TXT文件实现插入的.
...全文
43 7 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
lanren_me 2003-07-18
  • 打赏
  • 举报
回复
String s; //把数据保存;
int fhwnd;
s="c:\\aa";
String filename=ChangeFileExt(s,".DAT");
if (!FileExists(filename))
{
fhwnd=FileCreate(filename);
FileClose(fhwnd);
}
fhwnd=FileOpen(filename,fmOpenWrite);
FileSeek(fhwnd,0,2); //移动到文件尾;
s="asdfsfsafsadfsdfd";
int iFileLength=s.Length();
char *pszBuffer=new char[iFileLength];
pszBuffer=s.c_str();
FileWrite(fhwnd,pszBuffer,sizeof(char)*iFileLength);
FileClose(fhwnd);
lanren_me 2003-07-18
  • 打赏
  • 举报
回复
下边的代码不行吗?
FileSeek(iFileHandle,0,2); //移动到文件尾;
String s="asdfsfsafsadfsdfd";
int iFileLength=s.Length();
char *pszBuffer=new char[iFileLength];
pszBuffer=s.c_str();
FileWrite(iFileHandle,pszBuffer,sizeof(char)*iFileLength);

搞不懂你!!!!

xuv2002 2003-07-18
  • 打赏
  • 举报
回复
可以这么做
先读取插入位置之前的buffer 和 之后的buffer
然后新建或覆盖源文件
先写入之前的buffer 再写入插入文本
最后写入插入位置之后的buffer
FILE * hp = fopen("c:\\a.dat","rb");
if(hp==NULL) return;
fseek(hp,0,2);
int filelength = ftell(hp);
fseek(hp,0,0);
int insertpos = 3; //插入位置
char insertbuf [] = "xyz"; //插入文本
char * first = new char[insertpos+1];
memset(first,0,insertpos+1);
fread(first,1,insertpos,hp); //读取插入位置之前的buffer
char * second = new char[filelength-3+1];
memset(second,0,filelength-3+1);
fread(second,1,filelength-3,hp); //读取插入位置之后的buffer
fclose(hp);
hp = fopen("c:\\b.dat","wb+");
if(hp != NULL){
fwrite(first,1,insertpos,hp);
fwrite(insertbuf,1,strlen(insertbuf),hp);
fwrite(second,1,filelength-3,hp);
//分三次写入
fclose(hp);
}
delete [] first;
delete [] second;
alenwelkin 2003-07-18
  • 打赏
  • 举报
回复
将文件内容一次全部读到内存中,用一个数据结构记录下需要插入的位置以及要插入的字符串,用这两组数据进行合并式的写入,一个字符一个字符的写
duduwolf 2003-07-18
  • 打赏
  • 举报
回复
不要用ansistring,用char和标准的strcpy,strcat,strlen等进行操作,先找到插入点,然后把想插入的数据写进去,在把插入点后的数据循环重新写入,应该操作几十MB的文件不是问题吧?
lanren_me 2003-07-18
  • 打赏
  • 举报
回复
呵呵
FileSeek(iFileHandle,0,2); //移动到文件尾;
FileWrite(iFileHandle,pszBuffer,sizeof(char)*iFileLength);
lanren_me 2003-07-18
  • 打赏
  • 举报
回复
FileSeek(fhwnd,0,2); //移动到文件尾;
FileWrite(fhwnd,xdk,sizeof(iFileLength)*pszBuffer);

13,871

社区成员

发帖
与我相关
我的任务
社区描述
C++ Builder相关内容讨论区
社区管理员
  • 基础类社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧