1

I am attempting to create a program which writes the current username in text form (example John) to file on windows. I tried it through GetUserNameEx(NameDisplay, name, &size); but the output value is

002CF514

I tried this:

#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; } 
0

1 Answer 1

2

Since NameDisplay is a wide string, you have to use wofstream instead of ofstream. Also do not use TCHAR it is awfully deprecated thing. Use wchar_t instead. So correct version should be:

#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; } 

Update: Apparently Visual Studio always uses ANSI encoding to write a streams, so you have to imbue a locale to the fstream. Updated version of the code prints my user name in the Cyrillic locale correctly. You would have to change locale name for your country/language. See this answer for the additional info.

Sign up to request clarification or add additional context in comments.

8 Comments

Also do not use TCHAR it is awfully deprecated thing. Really? Since when?
@FrédéricHamidi Since Windows 98 era actually.
Sorry, that's complete nonsense. TCHAR has never been deprecated, and I've personally been using it far later than Windows 98 (and I'm not alone). The question I linked to in my previous comment also (partially) disagrees with you.
Why was this solution downvoted? It solves the problem. The OP's question explicitly defines UNICODE.
@Marek Updated my answer.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.