我的程序有两个显示文本文件中的文本的编辑控制框,它们都有与之关联的按钮,如果在编辑控制框中写入或删除了任何内容,这些按钮会更新与其关联的文本文件。我有这段代码可以从文本文件中读取
try
{
CStdioFile file(_T("1.txt"), CFile::modeRead);
CString str,mainstr = _T("");
while(file.ReadString(str))
{
mainstr += str;
mainstr += _T("\r\n");
}
CWnd *editwindow = this->GetDlgItem(IDC_EDIT2);
editwindow->SetWindowText(mainstr);
}
catch(CException* e)
{
MessageBox(_T("no such file"));
e->Delete();
}
然后这段代码写入文本文件
m_addtext.GetWindowText(m_adtxt);
if ( IsDlgButtonChecked(IDC_RADIO1) == BST_CHECKED )
{
CStdioFile file;
file.Open (_T("1.txt"), CFile::modeCreate | CFile::modeWrite);
file.WriteString (m_adtxt);
file.Close ();
}
对于我想要的,这一切都非常好,花花公子,但问题是,如果我在编辑框中删除一个字符,然后单击更新按钮,它会在单词后添加一个 block 字符。有时它甚至在每个单词后添加一个 block ,并在每个空行上添加一个 block 。只要它创建一个新文件并且没有删除任何内容,它就可以正常工作。我试过 null 终止,我试过 ccs="encoding"
。谁能指出我正确的方向?
最佳答案
作为MSDN says关于默认文本模式下的 CStdioFile
:
Text mode provides special processing for carriage return–linefeed pairs. When you write a newline character (0x0A) to a text-mode CStdioFile object, the byte pair (0x0D, 0x0A) is sent to the file. When you read, the byte pair (0x0D, 0x0A) is translated to a single 0x0A byte.
所以,虽然你的阅读看起来没问题,因为 \n
将被你使用的 ReadString
的重载剥离,然后你手动附加了 \r\n
以在编辑控件中正确显示,但是当您保存内容时,每个 \r\n
将被扩展为 \r\r\n
如上引述所述。
解决方案是在写入CStdioFile
之前从字符串中删除所有\r
字符,只留下\n
字符,然后让 CStdioFile
为您插入 \r
。或者,更简单的方法是,以二进制模式而不是文本模式打开文件以抑制这种转换:
CStdioFile file;
file.Open (_T("1.txt"), CFile::modeCreate | CFile::modeWrite | CFile::typeBinary);
file.WriteString(m_adtxt);
file.Close ();
关于c++ - 将文本写入文件后,mfc C++ 奇怪的 block 字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21095951/