簡體   English   中英

使用 CStdioFile 寫入字符串

[英]Using CStdioFile for writing string

我想將存儲在向量中的數據寫入文件。 因此,我使用以下例程:

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

問題是:盡管s中有數據,但輸出文件始終為NULL。 有人能解開這個謎嗎?

新的 MFC 項目創建為 Unicode,所以我假設這是 Unicode。

此外,您對(LPCTSTR)表明您遇到了錯誤,並且您嘗試通過強制轉換來修復(它不起作用)

您應該將文件創建為 Unicode,並使用寬字符串std::函數,例如std::wstringstd::wstringstream

例子:

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

編輯

順便說一句,您還可以使用std::wofstreampubsetbuf直接寫入 Unicode 流

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

同樣使用std::wifstream打開流

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM