Search code examples
c++linuxqtstlfstream

c++ opening file with non-Latin name


I have such files. I just want to open files with non-Latin names correctly.
I have no problems with files that have Latin names only with non-Latin names.

enter image description here

I use QDir for scanning directory and I hold names in QString, so it's held fine inside.

But there is a bottleneck with opening the file.
It gets so that I don't want to use QFile, I can use only C++ streams (more preferred) or C files.

When I want to open file, I do so:

fstream stream(source.toStdString().c_str(),ios_base::in | ios_base::binary);

After that I check whether attempt was successful:

  if(!stream.is_open())
   { cout<<"file wasn't opened " <<source.toStdString().c_str())<<"\n";
     return false; // cout was redirected to file // just a notice
   }

I get in my log file:
file wasn't opened /home/sh/.mozilla/firefox/004_??????? - ????? - ?????.mp3

It doesn't work for any file with non-Latin name and it does work fine for every file with Latin names.

I understand that this problem can be jumped over using QFile.

But I wonder, is it possible to get it done without third-party libraries or are there some another ways for solving it?

Thanks in advance for any tips.


Solution

  • Things are going wrong when you call toStdString() on your QString. It will convert the contents based on QTextCodec::codecForCStrings(), if it has been set, and latin-1 will be used otherwise. Latin-1 will collapse your non-latin characters to '?'s.

    Using source.toLocal8Bit().data() or source.toUtf8().data() instead will likely do what you want, but failing that you'll need to deal with QTextCodecs to get the right 8-bit encoding.