0

At first I built my project on Linux and it was built around streams.

When I started moving to Windows I ran into some problems.
I have a name of the file that I want to open in UTF-16 encoding. enter image description here

I try to do it using fstream:

QString source;  // content of  source  is shown on image
char *op= (char *) source.data();
fstream stream(op, std::ios::in | std::ios::binary);

But file cannot be opened.
When I check it,

 if(!stream.is_open())
   {}  // I always get that  it's not opened. But file indeed exists.

I tried to do it with wstream. But result is the same, because wstream accepts only char * too. As I understand it's so , because string , that is sent as char * , is truncated after the first zero and only one symbol of the file's name is sent, so file is never found. I know wfstream in Vissual studio can accept wchar_t * line as name, but compiler of my choice is MinGW and it doesn't have such signature for wstring constructor.

Is there any way to do it with STL streams?

ADDITION
That string can contaion not only Ascii symbols, it can contain Russian, German, Chinese symbols simultaneously. I don't want limit myself only to ASCII or local encoding.

NEXT ADDITION
Also data can be different, not only ASCII, otherwise I wouldn't bother myself with Unicode at all. E.g.

enter image description here

Thanks in advance!

Tebe
  • 3,176
  • 8
  • 40
  • 60

3 Answers3

3

Boost::Filesystem especially the fstream.hpp header may help.

Juraj Blaho
  • 13,301
  • 7
  • 50
  • 96
3

If you are using MSVC and it's implementation of the c++ standard library, something like this should work:

QString source;  // content of  source  is shown on image
wchar_t *op= source.data();
fstream stream(op, std::ios::in | std::ios::binary);

This works because the Microsoft c++ implementation has an extension to allow fstream to be opened with a wide character string.

karunski
  • 3,980
  • 2
  • 17
  • 10
0

Convert the UTF-16 string using WideCharToMultiByte with CP_ACP before passing the filename to fstream.

rasmus
  • 3,136
  • 17
  • 22
  • 2
    Not every file is accessible that way. If a filename has a char that is not present in the current ANSI code page ... – asveikau Jan 28 '13 at 19:05
  • Yes, but that's a limitation of the fstream implementation. – rasmus Jan 28 '13 at 19:07
  • 1
    Saying that the `fstream`s are limited and then pretending the problem doesn't exist seems like a bad idea to me. Is there some non-portable C++ class that will ultimately call `CreateFileW` to open the file? Seems like that would suit the questioner much better. – asveikau Jan 28 '13 at 19:11
  • For one, `QFile` has been suggested. – rasmus Jan 28 '13 at 19:14