简体   繁体   English

使用 CStdioFile 写入字符串

[英]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.问题是:尽管s中有数据,但输出文件始终为NULL。 Can anybody solve that mystery?有人能解开这个谜吗?

New MFC projects are created as Unicode, so I assume this is Unicode.新的 MFC 项目创建为 Unicode,所以我假设这是 Unicode。

Also your use of (LPCTSTR) suggests you are getting an error and you try to fix by casting (it doesn't work)此外,您对(LPCTSTR)表明您遇到了错误,并且您尝试通过强制转换来修复(它不起作用)

You should create the file as Unicode, and use wide string std:: functions such as std::wstring or std::wstringstream您应该将文件创建为 Unicode,并使用宽字符串std::函数,例如std::wstringstd::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::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"ελληνικά, ";

And similarly use std::wifstream to open the stream同样使用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