Home >Backend Development >C++ >How Can I Get the Execution Directory of My C/C Program Across Different Platforms?
In C/C , obtaining the full path to the directory from where a program is running can be a challenge for cross-platform applications. This article addresses this issue, providing solutions that cater to different platforms and filesystems.
Unfortunately, there is no standard C/C library function that returns the program's directory path in a platform-agnostic manner. However, using operating system-specific APIs can achieve this result.
On Windows, the GetModuleFileName function can retrieve the full path to the module (executable file).
char pBuf[256]; size_t len = sizeof(pBuf); int bytes = GetModuleFileName(NULL, pBuf, len); if (bytes) { return bytes; } else { return -1; // Error }
For Linux systems, the readlink function can access the symbolic link in "/proc/self/exe" to determine the program's executable file path.
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; } else { return -1; // Error }
Note that these approaches are specific to certain platforms and filesystems. If you require a more comprehensive solution, consider using cross-platform libraries like Boost.filesystem or Qt.
The above is the detailed content of How Can I Get the Execution Directory of My C/C Program Across Different Platforms?. For more information, please follow other related articles on the PHP Chinese website!