Daniel
Daniel

Reputation: 325

Creating a QFile with non-unicode name

I have a string in KOI8-R encoding, it's passed as argv, so initially it's a char* object. Using this deprecated encoding can't be helped at this point, unfortunately. The system locale is KOI8-R, and the source code is in this encoding too.

The string is a path to a file where some of the directories have names in KOI8-R. I need to open the file to write using QFile. However, open() always returns false no matter what I try.

I need to convert the path to QString to pass it to the constructor of QFile, however, straightforward conversion, QString::fromLocal8Bit() and QFile::decodeName() don't seem to help.

char* filename; // This is a KOI8-R string
QFile f(QString::fromLocal8Bit(filename));
// QFile f(QFile::decodeName(filename)) doesn't work too
f.open(QIODevice::WriteOnly | QIODevice::Text); // returns false

The only way I made it work was with the help of ofstream objects from STL, passing char* to ofstream constructor works fine, however, the use of QFile is much more preferable as the application is in QT.

Upvotes: 1

Views: 649

Answers (2)

Daniel
Daniel

Reputation: 325

The solution to this was to add QApplication initialization (QApplication a(argc, argv);) BEFORE doing anything with the strings. Apparently locale initialization is somewhere deep inside QApplication constructor.

Upvotes: 2

Lukáš Lalinský
Lukáš Lalinský

Reputation: 41306

Are you sure that the system uses a locale with the KOI8-R encoding? Qt uses the default locale's encoding to access the files, so if it's for example something that uses UTF-8, it won't be able to open a file with name in KOI8-R.

If the locale is different, you should be able to create a custom encoding function (e.g. using QTextCodec) to override this and set QFile to use it using QFile::setEncodingFunction().

Upvotes: 0

Related Questions