Determining the Program's Running Directory
To retrieve the full path of the directory from where a program is executing, various platform-specific methods can be employed. Here are two common approaches:
Windows:
Windows offers the GetModuleFileName function that returns the full path of the executing program. To use this, you can declare a character buffer (char pBuf[256]) to store the path and its length (size_t len = sizeof(pBuf)). Then, call GetModuleFileName passing NULL as the module handle and the buffer address as the second parameter. The function returns the length of the path in characters.
Linux:
On Linux, you can utilize the readlink function. It accepts the /proc/self/exe path as the source and a buffer address as the destination. The return value is the number of bytes written to the buffer, which must be less than its length (len - 1). Remember to append a null terminator after writing to the buffer.
This approach is not platform- or filesystem-agnostic. However, it provides a solution for specific platforms and filesystems, making it valuable for various scenarios.
The above is the detailed content of How Can I Determine a Program's Running Directory on Windows and Linux?. For more information, please follow other related articles on the PHP Chinese website!