0

i was wondering if there is any way to get the username in a c++ script, i need it to be working on windows and on linux.

in this moment im doing it like this:

#include <iostream>
#include <unistd.h> 
int getlogin_r(char *buf, size_t bufsize);
cout << getlogin()<< endl;


but of course it runs only in linux i thought about doing this using a function that works in both windows and linux or in some way switching the function based on the system.

  • Time to write yourself (or borrow from someone else) an OS abstraction layer. – user4581301 Jan 05 '23 at 20:38
  • There are several methods in [Linux](https://stackoverflow.com/questions/8953424/how-to-get-the-username-in-c-c-in-linux). Here is the method for [Windows](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-getusernamew) (comes in both -A and -W versions, as you wish.) Use `#ifdef _WIN32` to distinguish between the two operating systems. – Dúthomhas Jan 05 '23 at 21:30

1 Answers1

3

Such functionality is essentially non-portable and you have to rely on the system libraries supplied with your compiler. So it is not just a matter of OS but also of compiler and you need to be able to identify the compiler and code using conditional macros.

You can identify Visual Studio by the predefined symbol _MSC_VER. gcc defines __GNUC__. You can find more on the Web, e.g. https://gist.github.com/ByteProject/320483/f31b9524c367aad857fd1d4496af3c7e73e14291 but in principle the implementation should be validated on each.

  • Unless there is a magical (or POSIX) portable function that I am not aware of. –  Jan 05 '23 at 20:36