Get system username in Qt

There is no way to get the current username with Qt.

However, you can read this links :

http://www.qtcentre.org/threads/12965-Get-user-name http://qt-project.org/forums/viewthread/11951

I think the best method is :

#include <stdlib.h>

getenv("USER"); ///for MAc or Linux
getenv("USERNAME"); //for windows

EDIT : You can use qgetenv instead of getenv.


I was actually thinking about it a couple of days ago, and I came to the conclusion of having different alternatives, each with its own trade-off, namely:

Environment variables using qgetenv.

The advantage of this solution would be that it is really easy to implement. The drawback is that if the environment variable is set to something else, this solution is completely unreliable then.

#include <QString>
#include <QDebug>

int main()
{
    QString name = qgetenv("USER");
    if (name.isEmpty())
        name = qgetenv("USERNAME");
    qDebug() << name;
    return 0;
}

Home location with QStandardPaths

The advantage is that, it is relatively easy to implement, but then again, it can go unreliable easily since it is valid to use different username and "entry" in the user home location.

#include <QStandardPaths>
#include <QStringList>
#include <QDebug>
#include <QDir>

int main()
{
    QStringList homePath = QStandardPaths::standardLocations(QStandardPaths::HomeLocation);
    qDebug() << homePath.first().split(QDir::separator()).last();
    return 0;
}

Run external processes and use platform specific APIs

This is probably the most difficult to implement, but on the other hand, this seems to be the most reliable as it cannot be changed under the application so easily like with the environment variable or home location tricks. On Linux, you would use QProcess to invoke the usual whoami command, and on Windows, you would use the GetUserName WinAPI for this purpose.

#include <QCoreApplication>
#include <QProcess>
#include <QDebug>

int main(int argc, char **argv)
{
// Strictly pseudo code!
#ifdef Q_OS_WIN
    char acUserName[MAX_USERNAME];
    DWORD nUserName = sizeof(acUserName);
    if (GetUserName(acUserName, &nUserName))
        qDebug << acUserName;
    return 0;
#elif Q_OS_UNIX
    QCoreApplication coreApplication(argc, argv);
    QProcess process;
    QObject::connect(&process, &QProcess::finished, [&coreApplication, &process](int exitCode, QProcess::ExitStatus exitStatus) {
        qDebug() << process.readAllStandardOutput();
        coreApplication.quit();
    });
    process.start("whoami");
    return coreApplication.exec();
#endif
}

Summary: I would personally go for the last variant since, even though it is the most difficult to implement, that is the most reliable.

Tags:

C++

Qt

Qtcore