我正在尝试创建一个程序,以文本形式(例如 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/