【Qt】获取当前系统用户名:9种获取方式
  yQAl4kecrO8W 2023年12月23日 29 0


目的

有时,在项目开发中,需要显示或者用到当前系统用户名信息。以下是几种获取系统用户名解决方案:

解决方案

1. 使用QDir::home()

#include <QApplication>
#include <QDir>
#include <QDebug>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QDir dir;
    QString userName = dir.home().dirName();
    qDebug().noquote() << userName;
    return a.exec();
}

2. 使用QProcessEnvironment

#include <QApplication>
#include <QDebug>
#include <QProcessEnvironment>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
    // qDebug().noquote() << env.value("USER"); // Linux
    qDebug().noquote() << env.value("USERNAME"); // Windows
    return a.exec();
}

3. 使用QProcess

#include <QApplication>
#include <QDebug>
#include <QProcess>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QStringList env = QProcess::systemEnvironment();
    // foreach(QString envs, env){
    //     qDebug() << envs; // 输出所有系统配置
    int index = env.indexOf(QRegExp("USERNAME.*")); // 正则表达式,模糊匹配
    QString userName = env.at(index); // 字符串: "USERNAME=admin"
    // userName.remove(0,9); // 删去从首个字符开始的9个字符即"USERNAME="
    userName.remove("USERNAME=");
    qDebug().noquote() << userName;
    // }

    return a.exec();
}

4. 使用QHostInfo::localHostName(),建议这个

在.pro中配置

QT       += network
#include <QApplication>
#include <QDebug>
#include <QHostInfo>

int main(int argc ,char* argv[])
{
	QApplication a(argc, argv);
    QString machineName = QHostInfo::localHostName();
    qDebug().noquote() << machineName;
    return a.exec();
}

5. 使用qgetenvgetenv

#include <QApplication>
#include <QDebug>

int main(int argc ,char* argv[])
{
    QApplication a(argc, argv);
    // 可以使用qgetenv代替getenv

    // for MAc or Linux
    qDebug().noquote() << qgetenv("USER");
    // for windows
    qDebug().noquote() << getenv("USERNAME");

    return a.exec();
}

6. 使用QStandardPaths::standardLocations

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

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

7. 使用GetUserName

#include <QDebug>
#include <Windows.h>
#include <iostream>

#define UNLEN 128

int main() {
    TCHAR username[UNLEN + 1]; // 定义一个足够大的缓冲区来存储用户名
    DWORD usernameLength = UNLEN + 1; // 指定缓冲区的大小

    if (GetUserName(username, &usernameLength)) {
        std::wcout << L"当前系统用户名: " << username << std::endl; // 输出用户名
    } else {
        std::cout << "获取用户名失败,错误代码: " << GetLastError() << std::endl; // 输出错误信息
    }

    return 0;
}

8. 获取Linux系统用户名

#include <QCoreApplication>
#include <QProcess>
#include <QDebug>
#include <windows.h>
#include <iostream>

#define MAX_USERNAME 128

int main(int argc, char **argv)
{
// Strictly pseudo code!
#ifdef Q_OS_WIN
    wchar_t acUserName[MAX_USERNAME];
    DWORD nUserName = sizeof(acUserName);
    if (GetUserName(acUserName, &nUserName))
        std::cout << acUserName << std::endl;
    else {
        qDebug().noquote() << "aaa";
    }
        // 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
}

9. 使用命令获取Windows或Linux系统用户名

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

QString getSystemUsername()
{
    QString username;
    #ifdef Q_OS_WIN
        QProcess process;
        process.start("cmd.exe", QStringList() << "/c" << "echo %username%");
        process.waitForFinished();
        username = QString::fromLocal8Bit(process.readAllStandardOutput().trimmed());
    #elif defined(Q_OS_LINUX) || defined(Q_OS_MACOS)
        QProcess process;
        process.start("whoami");
        process.waitForFinished();
        username = QString::fromLocal8Bit(process.readAllStandardOutput()).trimmed();
    #endif
    return username;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QString username = getSystemUsername();
    qDebug() << "当前系统用户名:" << username;
    return a.exec();
}


【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年12月23日 0

暂无评论

推荐阅读
yQAl4kecrO8W