PDA

View Full Version : qgetenv and special chars



miraks
21st March 2009, 09:45
Hi,

When I try to retrieve values of environment variables with following code:

QString value=QString::fromLocal8Bit( qgetenv(iAttribute.toUtf8().constData()).constData () );

It doesn't work if the value contains special characters like french accents.

What is the solution ?

fullmetalcoder
21st March 2009, 09:49
It doesn't work if the value contains special characters like french accents.
Which value ? And what exactly does not work as expected? Do you get an empty QString? an ugly QString? something else?

miraks
21st March 2009, 10:02
If a export a variable like this:

export myvariable=développement

Then

QString value=QString::fromLocal8Bit( qgetenv("myvariable").constData() );
cout << "myvariable=" << value << endl;
returns:

myvariable=dveloppement

Accent is missing !

fullmetalcoder
21st March 2009, 10:15
are your sure that your locale support this caracter (locales handling under linux can be so tricky sometimes...)?

what is printed if you simply do this :



QByteArray value = qgetenv("myvariable");
qDebug("myvariable=%s", value.constData());

miraks
21st March 2009, 10:30
Hi,

I tried this:

QByteArray value = qgetenv("myvariable");
qDebug("myvariable=%s", value.constData());
cout << "myvariable=" << value.constData() << endl;
qDebug() << "myvariable=" << value.constData() << endl;


The result is:

myvariable=Développement
myvariable=Dveloppement
myvariable=Dveloppement


So, thank you for your help! No problem with qgetenv.
Why cout and qDebug() don't print correctly the value ?

ComaWhite
21st March 2009, 11:53
I think you would need to convert the 3 line to foo.toUtf8() and the 1st line implicitly coverts it to unicode. And cout STL doesn't handle unicode.

fullmetalcoder
21st March 2009, 13:48
That could be a side effect of implicit char* to QString casts, or improper locale settings which would make QString::fromLocal8Bit() use an improper text codec.

mimcimm
23rd October 2020, 09:10
The Qt environment manipulation functions are thread-safe, but this requires that the C library equivalent functions like getenv and putenv are not directly called.

To convert the data to a QString use QString::fromLocal8Bit().

Note: on desktop Windows, qgetenv() may produce data loss if the original string contains Unicode characters NOT representable in the ANSI encoding. Use qEnvironmentVariable() instead. On Unix systems, this function is lossless.

Link: https://doc.qt.io/qt-5/qtglobal.html#qgetenv (for more information)

ChrisW67
24th October 2020, 01:05
Wow, 11 years... got to be a new record for thread resurrection:)