S
S
Spark1082016-02-10 04:08:29
C++ / C#
Spark108, 2016-02-10 04:08:29

How to get current username in C++?

I want to get the username of the current Windows session, but nothing happens.

char buffer[256]; // буфер
  DWORD size; // размер
  size = sizeof(buffer); // размер буфера
  GetUserName(buffer, &size);
  string userName = buffer;

It throws an error in line 4, like char buffer does not match the LPWSTR type.
Even though the book says so.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
none7, 2016-02-10
@spark108

Windows indeed. In the headers, the function is defined like this:

BOOL WINAPI GetUserNameW(LPWSTR  lpBuffer, LPDWORD lpnSize);
BOOL WINAPI GetUserNameA(LPSTR  lpBuffer, LPDWORD lpnSize);
#ifdef _UNICODE
#define GetUserName GetUserNameW
#else
#define GetUserName GetUserNameA
#endif

Solutions to choose from:
And yes asd111 right, the buffer must be UNLEN+1 in size, otherwise a buffer overflow may occur, although this is unlikely.

A
asd111, 2016-02-10
@asd111

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

char username[UNLEN+1];
DWORD username_len = UNLEN+1;
GetUserName(username, &username_len);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question