wofstream

J

jraul

Why does the following code create an empty file? I am using Windows
XP.

#include <iostream>
#include <fstream>

int main()
{
std::wofstream fout("data.txt");

if( fout )
{
fout << L"\u2620\u262D\u262F" << std::endl;

fout.close();
}
}
 
J

John Harrison

jraul said:
Why does the following code create an empty file? I am using Windows
XP.

#include <iostream>
#include <fstream>

int main()
{
std::wofstream fout("data.txt");

if( fout )
{
fout << L"\u2620\u262D\u262F" << std::endl;

fout.close();
}
}

Probably because the character \u2620 cannot be represented in your
current code page.

john
 
J

James Kanze

Why does the following code create an empty file? I am using Windows
XP.
#include <iostream>
#include <fstream>
int main()
{
std::wofstream fout("data.txt");

This creates a stream using the current default locale. Since
you haven't set the locale, you get the "C" locale.
if( fout )
{
fout << L"\u2620\u262D\u262F" << std::endl;

And there's no such character as "\u2620" in the "C" locale, so
conversion fails, which causes the output to fail, which means
that no further output can occur until you clear() the error
status.

Unless you are restricting your characters to US ASCII (and
if so, why bother with wofstream), you're main() should almost
always start:

std::locale::global( std::locale( "" ) ) ;
std::wcout.imbue( std::locale() ) ;
std::wcin.imbue( std::locale() ) ;
std::wcerr.imbue( std::locale() ) ;

Otherwise, it is probable that trying to output any character
not in the basic execution character set may fail. (Actually,
most implementations allow a few additional characters, such as
'$' or '@'. But this is not guaranteed. Of course, nothing you
do with the locales is really guaranteed either. If the user is
in a locale where there is no character "\u2620"---which would
be my case, for example---then you'll still end up with an
error. And to refer vaguely to another thread here: if the user
has selects a font with a different encoding than that of the
locale when he views the file, who knows what he'll get. But
the lines above make it the user's problem, and not yours:).)
 
K

Kevin Handy

jraul said:
Why does the following code create an empty file? I am using Windows
XP.

#include <iostream>
#include <fstream>

int main()
{
std::wofstream fout("data.txt");

if( fout )

What is fout at this point?

If the 'if' statement fails, don't expect the code
within to be executed.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,533
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top