Created
August 5, 2024 07:54
-
-
Save dezashibi/f835af7cd8a3a63b336685bf2efd9d6d to your computer and use it in GitHub Desktop.
Get user's home directory on Windows and POSIX operating systems
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#ifdef _WIN32 | |
#include <windows.h> | |
#endif | |
const char* get_home_directory() | |
{ | |
#ifdef _WIN32 | |
static char home_dir[MAX_PATH]; | |
if (GetEnvironmentVariable("USERPROFILE", home_dir, MAX_PATH)) | |
{ | |
return home_dir; | |
} | |
else | |
{ | |
return NULL; | |
} | |
#else | |
return getenv("HOME"); | |
#endif | |
} | |
int main() | |
{ | |
const char* home_dir = get_home_directory(); | |
if (home_dir != NULL) | |
{ | |
printf("Home directory: %s\n", home_dir); | |
} | |
else | |
{ | |
printf("Failed to get home directory.\n"); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment