user3179762
user3179762

Reputation: 19

mfc c++ strange block characters after text written to file

my program has two edit control boxes that display text from a text file, and they both have buttons associated with them that update the text files associated with them if anything is written or deleted in the edit control boxes. i have this code to read from a text file

    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();

}

and then this code to write to the text file

    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 ();
}

it all works pretty much fine and dandy for what i want, but the problem is is that it adds a block character after a word if i delete a character in the edit box, and then click the update button. sometimes it even adds a block after every word and one block on every empty line. it works fine as long as it creates a new file and nothing is deleted. i've tried null terminating, i've tried ccs="encoding". can anyone point me in the right direction?

Upvotes: 0

Views: 1228

Answers (1)

Roger Rowland
Roger Rowland

Reputation: 26259

As MSDN says about CStdioFile in its default of text mode:

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.

So, although your reading looks ok, because the \n will be stripped off by the overload of ReadString that you use, then you have manually appended \r\n to display correctly in an edit control, however when you save the contents, every \r\n will be explanded to \r\r\n as described in the quote above.

The solution is either to remove all of the \r characters from the string before writing to CStdioFile, leaving just the \n characters, and let CStdioFile insert the \r for you. Or, much easier, just open the file in binary mode rather than text mode to suppress this conversion:

CStdioFile file;
file.Open (_T("1.txt"), CFile::modeCreate | CFile::modeWrite | CFile::typeBinary);
file.WriteString(m_adtxt);
file.Close ();

Upvotes: 1

Related Questions