How to Determine the Execution Directory in a Cross-Platform Environment
In the realm of programming, determining the execution directory of a program is a crucial yet platform- and filesystem-dependent task. C and C developers often seek a universal solution that transcends these dependencies.
While there may not be a completely platform-agnostic method, here are tailored solutions for Windows and Linux:
Windows:
#include <windows.h> int main() { char pBuf[256]; size_t len = sizeof(pBuf); int bytes = GetModuleFileName(NULL, pBuf, len); printf("Execution directory: %s", pBuf); return 0; }
Linux:
#include <unistd.h> #include <string.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] = ''; printf("Execution directory: %s", pBuf); return 0; }
The above is the detailed content of How Can I Get the Execution Directory in a Cross-Platform C/C Program?. For more information, please follow other related articles on the PHP Chinese website!