我想只改寫文本的第一行數據
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);
}