我想只改写文本的第一行数据
void EditView::WriteInTitle(CString strName, CString lpsz)
{
CFile WriteFile;
WriteFile.Open(strName, CFile::modeWrite | CFile::modeRead | CFile::typeBinary);
CString subStr = "\r"; //要被删除的子串
int index = lpsz.Find(subStr);
while (index!= -1)
{
lpsz.Delete(index, subStr.GetAllocLength());
index = lpsz.Find(subStr);
}
lpsz = lpsz + "\r\n";
LPCTSTR s = lpsz.GetBuffer(lpsz.GetLength());
WriteFile.Write(s, lpsz.GetLength()*sizeof(CHAR));
WriteFile.Close();
}
但是我覆盖了第一行后,后面就乱码了。。
目测是写入长度出问题了。。应该是覆盖到了第二行的文字。
但是这里长度不对吗?为什么会超出第一行的文字长度?
CString ReplaceFirstLine(CString s, CString newline)
{
if (s.IsEmpty()) return newline;
LPCTSTR sc = (LPCTSTR)s;
int i;
int p = -1;
for (i = 0; i < strlen(sc) - 1; i++)
{
if (sc[i] == '\r' && sc[i + 1] == '\n')
{
p = i;
break;
}
}
if (p == -1) return newline;
return CString(newline + CString(sc + i));
}
void CApp2Dlg::OnButton1()
{
// TODO: Add your control notification handler code here
CString str;
CString t = "title";
m_edit.GetWindowText(str);
str = ReplaceFirstLine(str, t);
m_edit.SetWindowText((LPCTSTR)str);
}
CString subStr = "\r"; //要被删除的子串
int index = lpsz.Find(subStr);
while (index!= -1)
{
lpsz.Delete(index, subStr.GetAllocLength());
index = lpsz.Find(subStr);
}
这段代码是把数据内的换行符去掉,只在末尾加换行符。(因为每写入一次末尾都会加一个换行符)
代码没有考虑 \r 和 \r\n,如果 \r\n只Delete掉\r就破坏文本内容 了
Remarks
Call this member (CString::Delete) function to delete a character or characters from a string starting with the character at nIndex.