Problem:
Determining the full path of the directory where a program executes is a fundamental task in many programming scenarios. However, achieving this across various platforms and file systems can be challenging due to system-specific implementations. Can you provide a concise and efficient method to accomplish this platform-agnostically?
Solution:
Depending on the operating system, there are distinct approaches to retrieve this information:
#include <windows.h> int main() { char pBuf[256]; size_t len = sizeof(pBuf); int bytes = GetModuleFileName(NULL, pBuf, len); return bytes ? bytes : -1; }
#include <string.h> #include <unistd.h> int main() { 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; }
These methods rely on low-level system functions to obtain the path directly from the operating system, ensuring platform-agnostic functionality.
The above is the detailed content of How Can I Get a C/C Program's Execution Directory Cross-Platform?. For more information, please follow other related articles on the PHP Chinese website!