Search code examples
c++stringmfccfile

Using CStdioFile for writing string


I want to write data stored in a vector into a file. Therefore I use the following routine:

bool Grid::saveToFile() {
    stringstream sstream;
    for (size_t i = 0; i < taglist.size(); ++i)
    {
        if (i != 0)
            sstream << ",";
        sstream << taglist[i];
    }
    string s = sstream.str();

    CFileDialog FileDlg(FALSE);

    if (FileDlg.DoModal() == IDOK) {
        CString pathName = FileDlg.GetPathName();
        CStdioFile outputFile(pathName, CFile::modeWrite | CFile::modeCreate);
        outputFile.WriteString((LPCTSTR)s.c_str());
        outputFile.Close();
        return TRUE;
    }

    return FALSE;
}

The problem is: Although there's data in s, the output file is always NULL. Can anybody solve that mystery?


Solution

  • New MFC projects are created as Unicode, so I assume this is Unicode.

    Also your use of (LPCTSTR) suggests you are getting an error and you try to fix by casting (it doesn't work)

    You should create the file as Unicode, and use wide string std:: functions such as std::wstring or std::wstringstream

    Example:

    CStdioFile f(L"test.txt", 
        CFile::modeWrite | CFile::modeCreate | CFile::typeUnicode);
    
    std::wstringstream ss;
    ss << L"Test123\r\n";
    ss << L"ελληνικά\r\n";
    
    f.WriteString(ss.str().c_str());
    

    Edit

    By the way, you can also use std::wofstream with pubsetbuf to write directly to stream in Unicode

    std::wofstream fout(L"test.txt", std::ios::binary);
    wchar_t buf[128];
    fout.rdbuf()->pubsetbuf(buf, 128);
    fout << L"Test1234, ";
    fout << L"ελληνικά, ";
    

    And similarly use std::wifstream to open the stream

    std::wifstream fin(L"test.txt", std::ios::binary);
    wchar_t buf[128];
    fin.rdbuf()->pubsetbuf(buf, 128);