c++ - 将当前用户名写入Windows中的文件

标签 c++ windows

我正在尝试创建一个程序,以文本形式(例如 John)将当前用户名写入 Windows 文件。我通过 GetUserNameEx(NameDisplay, name, &size); 尝试过,但输出值为

002CF514

我试过这个:

#ifndef _UNICODE
#define _UNICODE
#define UNICODE
#endif

#define WIN32_LEAN_AND_MEAN
#include <Windows.h>

#define SECURITY_WIN32
#include <Security.h>

#include <iostream>
#include <Lmcons.h>
#include <fstream>

#pragma comment(lib, "Secur32.lib")

using namespace std;

int main(void)
{
    TCHAR name[UNLEN + 1];
    DWORD size = UNLEN + 1;

    GetUserNameEx(NameDisplay, name, &size);

    ofstream File;
    File.open("NAME.TXT", ios::app);
    File << name;
    File.close();

    return 0;
}

最佳答案

由于 NameDisplay 是一个宽字符串,您必须使用 wofstream 而不是 ofstream。也不要使用 TCHAR 它是 awfully deprecated thing .请改用 wchar_t。所以正确的版本应该是:

#ifndef _UNICODE
#define _UNICODE
#define UNICODE
#endif

#define WIN32_LEAN_AND_MEAN
#include <Windows.h>

#define SECURITY_WIN32
#include <Security.h>

#include <iostream>
#include <Lmcons.h>
#include <fstream>

#pragma comment(lib, "Secur32.lib")

using namespace std;

int main(void)
{
    wchar_t name[UNLEN + 1];
    DWORD size = UNLEN + 1;

    GetUserNameEx(NameDisplay, name, &size);

    std::locale::global(std::locale("Russian_Russia"));
    wofstream File;
    File.open("NAME.TXT", ios::app);
    File << name;
    File.close();

    return 0;
}

更新:显然 Visual Studio 总是使用 ANSI 编码来编写流,因此您必须为 fstream 注入(inject)语言环境。代码的更新版本在西里尔语言环境中正确地打印了我的用户名。您将不得不更改您所在国家/地区/语言的区域设置名称。参见 this回答附加信息。

关于c++ - 将当前用户名写入Windows中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39467135/

相关文章:

c++ - 任何人都有一个很好的 C++ 共享内存容器?

c++ - boost::shared_ptr<TTransport> 是否在销毁后关闭连接?

C++ 和进程内存保护

java - 在 Linux 上运行 Java 调用 native .so 时持续存在 UnsatisfiedLinkError

C++解析字符串以查找出现

windows - Batch/cmd for 循环语法错误

windows - 停止/启动服务 - 处理 STOP_PENDING 和 START_PENDING

c - 在文件夹中打开文件时运行 .exe 文件

c++ - 矩阵乘法及其转置

Python、Windows服务导入报错