[flang-commits] [flang] GETLOG runtime and extension implementation: get login username (PR #70917)

Yi Wu via flang-commits flang-commits at lists.llvm.org
Fri Nov 10 02:41:38 PST 2023


================
@@ -14,6 +14,37 @@
 #include "flang/Runtime/descriptor.h"
 #include <cstdlib>
 #include <limits>
+#include <string.h>
+
+#ifdef _WIN32
+#define WIN32_LEAN_AND_MEAN
+#define NOMINMAX
+#include <windows.h>
+
+#include <lmcons.h> // UNLEN=256
+#include <wchar.h> // wchar_t cast to LPWSTR
+#pragma comment(lib, "Advapi32.lib") // Link Advapi32.lib for GetUserName
+
+static inline char *getlogin() {
+  static char username[UNLEN + 1];
+  wchar_t w_username[UNLEN + 1];
+  DWORD namelen = sizeof(w_username) / sizeof(w_username[0]);
+
+  if (GetUserName(w_username, &namelen)) {
+    // Convert the wchar_t string to a regular C string
+    if (wcstombs(username, w_username, UNLEN + 1) == -1) {
+      // Conversion failed
+      return NULL;
+    }
+    return (username[0] == 0 ? NULL : username);
+  } else {
+    return NULL;
+  }
+  return nullptr;
+}
+#else
+#include <unistd.h>
----------------
PAX-12-WU wrote:

I will use a `__has_include(<unistd.h>)` to check if its posix-compliant

https://github.com/llvm/llvm-project/pull/70917


More information about the flang-commits mailing list