I am Creating a MFC Application to Read a Text file into a Edit Box. I am implementing the following code

FILE *m_pFile ;
    CString m_strLine , m_strText;
    char line [1000] = "" ;

    m_pFile = fopen ( "C:\\SELF.txt" , "r" ) ;
        
    if ( m_pFile != NULL ) 
    {
        // read each line in the file
        while(fgets(line,sizeof(line),m_pFile) != NULL)
        {
            // convert the line to a CString
            m_strLine = line ; 

            // format the string for the edit control
            m_strLine.Replace ( '\n' , '\r\n' );    //PROBLEM HERE

            // store each line to the text string
            m_strText += m_strLine ; 
        }
    }

    // write all the text to the edit box at once
    GetDlgItem(IDC_EDIT1)->SetWindowTextW( m_strText ) ;

    // close the file
    fclose ( m_pFile );

All The text is appearing without the line feed. Please Help!!! :'(
I am Using Visual Studio 2008.

Alternate Suggestions are Welcome.

You want

m_strLine.Replace("\n", "\r\n");

>> m_strLine.Replace ( '\n' , '\r\n' );

That should give you a warning or two, are you ignoring compiler warnings?

You want

m_strLine.Replace("\n", "\r\n");

>> m_strLine.Replace ( '\n' , '\r\n' );

That should give you a warning or two, are you ignoring compiler warnings?

m_strLine.Replace("\n", "\r\n");
is giving a error
cannot covert from const char [2] to wchar_t

Alright, then wrap the string literals with the _T() macro (from <tchar.h>), like so;

m_strLine.Replace(_T("\n"), _T("\r\n"));

>>cannot covert from const char [2] to wchar_t
Hummm. If you are compiling the program for UNICODE then why aren't you getting similar errors on all the other lines in your program (such as line 5)?

You could have avoided that problem altogether had you used ifstream and getline() instead of C's FILE and associated C functions.

>> If you are compiling the program for UNICODE then why aren't you getting similar errors on all the other lines in your program (such as line 5)? fopen() is the non-UNICODE version, so the code is valid as such - although it is confusing. One option would be to completely stick with MFC i.e. using CStdioFile/CString for reading the file.

Alright, then wrap the string literals with the _T() macro (from <tchar.h>), like so;

m_strLine.Replace(_T("\n"), _T("\r\n"));

Thanks So Much.. It worked. Thanks again.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.