c - 如何获取MinGW中的用户名?

标签 c mingw

要使用 MinGW 从 Windows 获取用户名,我应该使用 unistd.h 中的函数 getlogin() 还是 Windows 函数 GetUserName?

谢谢。

最佳答案

您可以检查USERNAME变量:

char *name = getenv("USERNAME"); // Get environmentvariable for Username

if( name == NULL )
    return -1; // Username not found ...
else
    printf("%s\n", name); // Output Username

如果您完全使用 Windows,您也可以使用它的 API (GetUserName()):

#include <windows.h>
#include <Lmcons.h>

// ...

TCHAR name [ UNLEN + 1 ];
DWORD size = UNLEN + 1;

if( GetUserName((TCHAR*) name, &size) )
    printf("%s\n", name); // Output Username
else
    return -1; // Username not found ...

一般情况:

  • 如果您使用的是 linux/unix,请使用 getlogin(),因为它在 MinGW 中可用<
  • 如果您使用的是Windows,请使用GetUserName()
  • 如果您想保持平台独立性,请使用两者(条件组预处理器)

关于c - 如何获取MinGW中的用户名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13612199/

相关文章:

对 memset 感到困惑

c - 添加指向字符的指针

c - 格式化 unsigned long long 会导致整数溢出

ios - 如何将 Obj-C block 保存在 C 结构中?

c - 尝试访问结构中的指针时出现段错误

CMake:找到使用 MinGW/MSYS 构建的 wxWidgets?

c++ - 如何在 Windows 上编译 64 位版本的 ffmpeg?

mingw - 为什么 MinGW 没有出现在 Eclipse/Indigo CDT 工具链列表中?

c++ - C语言有前置自增和后置自增的历史原因是什么?

c - `atoi` 这个名字是从哪里来的?