Is there any cross platform way to get the current username in a Qt C++ program?
I've crawled the internet and the documentation for a solution, but the only thing I find are OS dependent system calls.
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:
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; }
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; }
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With