Home > Backend Development > C++ > How Can I Get the Execution Directory of My C/C Program Across Different Platforms?

How Can I Get the Execution Directory of My C/C Program Across Different Platforms?

Susan Sarandon
Release: 2024-12-24 17:49:09
Original
918 people have browsed it

How Can I Get the Execution Directory of My C/C   Program Across Different Platforms?

Determining the Program's Directory

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.

Platform-Agnostic Approaches

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.

Windows

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
}
Copy after login

Linux

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
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template