C++ 在windows中将当前用户名写入文件
我正在尝试创建一个程序,将当前用户名以文本形式(例如John)写入windows上的文件。我通过C++ 在windows中将当前用户名写入文件,c++,windows,C++,Windows,我正在尝试创建一个程序,将当前用户名以文本形式(例如John)写入windows上的文件。我通过GetUserNameEx(名称显示、名称和大小)进行了尝试但输出值为 002CF514 我试过这个: #ifndef _UNICODE #define _UNICODE #define UNICODE #endif #define WIN32_LEAN_AND_MEAN #include <Windows.h> #define SECURITY_WIN32 #include <
GetUserNameEx(名称显示、名称和大小)进行了尝试代码>但输出值为
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;
}
\ifndef\u UNICODE
#定义UNICODE
#定义UNICODE
#恩迪夫
#定义WIN32_精益_和_平均值
#包括
#在WIN32中定义安全性
#包括
#包括
#包括
#包括
#pragma注释(lib,“Secur32.lib”)
使用名称空间std;
内部主(空)
{
TCHAR名称[UNLEN+1];
DWORD大小=UNLEN+1;
GetUserNameEx(名称显示、名称和大小);
流文件;
打开(“NAME.TXT”,ios::app);
文件由于namediplay
是一个宽字符串,您必须使用wofstream
而不是流的。也不要使用TCHAR
。而是使用wchar\u 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;
}
\ifndef\u UNICODE
#定义UNICODE
#定义UNICODE
#恩迪夫
#定义WIN32_精益_和_平均值
#包括
#在WIN32中定义安全性
#包括
#包括
#包括
#包括
#pragma注释(lib,“Secur32.lib”)
使用名称空间std;
内部主(空)
{
wchar_t名称[UNLEN+1];
DWORD大小=UNLEN+1;
GetUserNameEx(名称显示、名称和大小);
std::locale::global(std::locale(“俄罗斯”);
wofstream文件;
打开(“NAME.TXT”,ios::app);
文件也不使用TCHAR这是一个非常不推荐的东西。从什么时候开始?@FrédéricHamidi实际上是从Windows 98时代开始的。对不起,这完全是胡说八道。TCHAR
从来没有被反对过,我个人使用它的时间比Windows 98晚得多(我并不孤单)。我在之前的评论中也(部分地)提到了这个问题不同意你的观点。为什么这个解决方案被否决了?它解决了问题。OP的问题明确定义了UNICODE。@Marek更新了我的答案。