Obtaining the Program's Directory in C/C Across Platforms and File Systems
In many scenarios, it becomes necessary to determine the directory from which a program is running. This information can be valuable for various purposes, such as accessing configuration files or logging. However, obtaining this directory in a platform-agnostic and filesystem-agnostic manner can pose a challenge.
Standard Approaches
The standard C/C library, unfortunately, does not provide a standard function for this purpose. For platform-specific solutions, the situation is as follows:
Windows
On Windows systems, the GetModuleFileName function can be used to retrieve the full path to the executing application.
char pBuf[256]; size_t len = sizeof(pBuf); int bytes = GetModuleFileName(NULL, pBuf, len); return bytes ? bytes : -1;
Linux
For Linux systems, the readlink function can be utilized to read the symbolic link pointing to the executing program.
char pBuf[256]; size_t len = sizeof(pBuf); int bytes = MIN(readlink("/proc/self/exe", pBuf, len), len - 1); if (bytes >= 0) pBuf[bytes] = ''; return bytes;
The above is the detailed content of How Can I Get a Program's Directory in C/C Across Different Platforms?. For more information, please follow other related articles on the PHP Chinese website!