Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
123 views
in Technique[技术] by (71.8m points)

c++ - Wrote to a file using std::wofstream. The file remained empty

I wrote the following program using VS2008:

#include <fstream>
int main()
{
    std::wofstream fout("myfile");
    fout << L"???????? Россия ?sterreich Ελλ?δα ????" << std::endl;
}

When I tried to compile it the IDE asked me whether I wanted to save my source file in unicode, I said "yes, please".
Then I run the program, and myfile appeared in my project's folder. I opened it with notepad, the file was empty. I recalled that notepad supported only ASCII data. I opened it with WordPad, it was still empty. Finally the little genius inside me urged me to look at the file size and not surprisingly it was 0 bytes. So I rebuilt and reran the program, to no effect. Finally I decided to ask very intelligent people on StackOverflow as to what I am missing and here I am :)

Edited:

After the abovementioned intelligent people left some comments, I decided to follow their advice and rewrote the program like this:

#include <fstream>
#include <iostream>
int main()
{
    std::wofstream fout("myfile");
    if(!fout.is_open())
    {
        std::cout << "Before: Not open...
";
    }
    fout << L"???????? Россия ?sterreich Ελλ?δα ????" << std::endl;
    if(!fout.good())
    {
        std::cout << "After: Not good...
";
    }
}

Built it. Ran it. And... the console clearly read, to my surprise: "After: Not good...". So I edited my post to provide the new information and started waiting for answers which would explain why this is and what I could do. :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

MSVC offers the codecvt_utf8 locale facet for this problem.

#include <codecvt>

// ...  
std::wofstream fout(fileName);
std::locale loc(std::locale::classic(), new std::codecvt_utf8<wchar_t>);
fout.imbue(loc);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...