How to Acquire User Home Directory in Linux/Unix
For C applications running on Linux systems, the user's home directory can be retrieved without the use of the HOME environment variable. Here's a solution that aligns with this requirement:
To obtain the home directory, follow these steps:
Example Code:
<code class="cpp">#include <unistd.h> // for getuid #include <sys/types.h> // for getpwuid #include <pwd.h> // for getpwuid struct passwd *pw = getpwuid(getuid()); const char *homedir = pw->pw_dir;</code>
Now, the homedir variable stores the path to the user's home directory.
Note for Root Users:
When a program runs as the root user, it is generally considered unsafe to create files or folders in the /root directory. Instead, it's recommended to create a specific directory within /root for storing program-related data or logs.
The above is the detailed content of How to Retrieve the User Home Directory in Linux/Unix without Using the HOME Environment Variable?. For more information, please follow other related articles on the PHP Chinese website!