读书人

关于MFC删除文本文件指定字符串的有关

发布时间: 2012-05-27 05:42:30 作者: rapoo

关于MFC删除文本文件指定字符串的问题,求真正高手不厌其烦,热心指教
删除字符串的响应函数:
int item;
item=m_listroom.GetSelectionMark();//获取当前列表视图选中项的索引
if(item==-1)//没有选择返回值为-1
{
MessageBox("请选择已添加的设备!");
}
else
{
CString str_room;//存放 房间的字符串
CString str_ip;//IP
CString isLink;//连接状态
CString isOpen;//isOpen
CString str_file;//存放文本中的内容
CString str;//存放选定列表控件索引的内容
int str_length;//存放选定列表控件索引内容的大小
int str_find;//存放选定列表控件索引内容的第一个字符的索引
/*******************
构建文本对象
********************/
CFile file("IP_ROOM.txt",CFile::modeReadWrite);
int FileLength=file.GetLength();
char* pBuf;
pBuf=new char[FileLength+1];
pBuf[FileLength]=0;
file.Read(pBuf,FileLength);
str_file=pBuf;



str_room=m_listroom.GetItemText(item,0);
str_ip=m_listroom.GetItemText(item,1);//item为选定的行索引,后面为列索引
isLink=m_listroom.GetItemText(item,2);
isOpen=m_listroom.GetItemText(item,3);
str=str_room+" "+str_ip+" "+isLink+" "+isOpen+"\r\n";

m_listroom.DeleteItem(item);//从列表控件删除选中的项目
str_file.Replace(str,"");
file.Write(str_file,str_file.GetLength());
MessageBox(str_file);
file.Close();
}
写入文件时的函数:
CString str;
str=str_room+" "+str_ip+" "+isLink+" "+isOpen;//合成一句
CFile file("IP_ROOM.txt",CFile::modeCreate|CFile::modeNoTruncate|CFile::modeWrite);
if(file.GetLength()!=0)//判断是否文件为空,非空的话不需要换行
{
file.SeekToEnd();
file.Write("\r\n",strlen("\r\n"));//换行
}
file.Write(str,strlen(str));
file.Close();
刚开始时TXT文件内容为:
1#21 111.120.210.101 已连接 开启
1#451 0.0.0.0 已连接 开启
1#11 222.222.222.222 已连接 开启
列表控件显示顺序是:
1#11 222.222.222.222 已连接 开启
1#451 0.0.0.0 已连接 开启
1#21 111.120.210.101 已连接 开启

执行删除函数:1#451 0.0.0.0 已连接 开启
MessageBox(str_file);显示:
1#21 111.120.210.101 已连接 开启
1#11 222.222.222.222 已连接 开启
但文本TXT内容却变为:
1#21 111.120.210.101 已连接 开启
1#451 0.0.0.0 已连接 开启
1#11 222.222.222.222 已连接 开启1#21 111.120.210.101 已连接 开启
1#11 222.222.222.222 已连接 开启



[解决办法]
简单的做法是将以前的全部覆盖
[解决办法]

探讨
……
str_file.Replace(str,"");
DWORD dwSize = str_file.GetLength()*sizeof(TCHAR);
file.SetLength(dwSize);
file.SeekToBegin();
file.Write(str_file, dwSize);
file.Close();

[解决办法]
file.Read(pBuf,FileLength);

这个以后指针位置就变到了文件尾了
在执行下面这句
file.Write(str_file,str_file.GetLength());
就相当于在文件尾加数据了

读书人网 >VC/MFC

热点推荐