Skip to content

Instantly share code, notes, and snippets.

@dezashibi
Created August 5, 2024 07:54
Show Gist options
  • Save dezashibi/f835af7cd8a3a63b336685bf2efd9d6d to your computer and use it in GitHub Desktop.
Save dezashibi/f835af7cd8a3a63b336685bf2efd9d6d to your computer and use it in GitHub Desktop.
Get user's home directory on Windows and POSIX operating systems
#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