Sign in to follow this  
dmatter

Whats the propper way to read/write wchar_t to iofstreams?

Recommended Posts

take the following code which creates an error from trying to read a wchar_t:
ifstream ifs("somefile.txt");
wchar_t wct = 5;
ifs >> wct;
What is the correct or usual way to read and write a wchar_t? What about the following (havn't tested it):
ifstream ifs("somefile.txt");
wchar_t wct = 5;
ifs.read((char*)&wct, sizeof(wchar_t));
Its curious why the first snippit doesn't work, perhaps wchar_t isn't portable? Any insights are helpful Thanks

Share this post


Link to post
Share on other sites
wchar_t is portable, it's just the standard library prefers it when you keep the type of streams and strings matched. For example using a wifstream if you're going to read wchar_ts. Though, keep in mind that depending on your compiler, you may want to imbue a codecvt on the stream before doing any reading or writing of wide characters.

Share this post


Link to post
Share on other sites
Quote:
Original post by SiCrane
wchar_t is portable, it's just the standard library prefers it when you keep the type of streams and strings matched. For example using a wifstream if you're going to read wchar_ts.

I was half aware of wifstream but isn't it possible to read it from a normal ifstream?
Or can i use a wifstream instead but also read the usual char type?

Quote:
Original post by SiCrane
Though, keep in mind that depending on your compiler, you may want to imbue a codecvt on the stream before doing any reading or writing of wide characters

What would that do exactly (imbue isn't in my vocabulary [sad]).

Would my second snippet of code work for reading a wchar_t?

Edit: what about casting to a 'signed short int'? It doesn't have to be human readable in the actual file.

[Edited by - dmatter on August 30, 2005 5:18:01 PM]

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this