0

I am working on a Qt project and I want the working directories to be dynamically set for the program will be run on different systems.

I have enclosed the code for your reference.

QProcess Home;
Home.start("echo",QStringList() << "$HOME");
Home.waitForFinished(-1);
qDebug() << Home.readAllStandardOutput();

But the qDebug() prints "$HOME" and not the actual home path. Why does this happen? Is There any other way of doing this?

4 Answers4

3

You can use std::getenv to retrieve the home path set in the processes environment.

#include <cstdlib>

const char *homePath = std::getenv("HOME");
if(homePath != NULL)
{
    QProcess Home;
    Home.start("echo",QStringList() << homePath);
    Home.waitForFinished(-1);
    qDebug() << Home.readAllStandardOutput();
}
Captain Obvlious
  • 19,754
  • 5
  • 44
  • 74
  • 2
    You can also use `QDir::homePath()` to get the home path. And `qgetenv` can be used instead of `std::getenv`. – Pavel Strakhov Jul 02 '13 at 06:39
  • +1 for `QDir::homePath()`. That works on Windows, too. `$HOME` is POSIX. – MSalters Jul 02 '13 at 12:05
  • @Riateche, thank you that really helped but now I have another problem. I can access $HOME, but I can't access other user defined environment variables. Would be great if you can help me out with this. – Samridhi Singhi Jul 04 '13 at 05:07
1

Here is another way to do it.

QStringList QProcess::systemEnvironment () [static]

http://qt-project.org/doc/qt-4.8/qprocess.html#systemEnvironment

 QStringList environment = QProcess::systemEnvironment();
  // environment = {"PATH=/usr/bin:/usr/local/bin",
  //                "USER=greg", "HOME=/home/greg"}

Hope that helps.

phyatt
  • 18,472
  • 5
  • 61
  • 80
0

QByteArray qgetenv ( const char * varName ) is the function provided by QT library to fetch any environment variable on all platforms.

getenv() seems to be deprecated on Windows VS2005 onward more info here

ankit.ckt
  • 83
  • 4
0

Especially for home path you should use QDir::homePath()

kwirz
  • 76
  • 2
  • thank you,it really helped, but now I want to access userdefined environment variables. qgetenv doesn't give me the answer. Please help me out. – Samridhi Singhi Jul 04 '13 at 05:13