Home >Backend Development >C++ >How Can I Get the Execution Directory in a Cross-Platform C/C Program?

How Can I Get the Execution Directory in a Cross-Platform C/C Program?

DDD
DDDOriginal
2024-12-21 02:48:12789browse

How Can I Get the Execution Directory in a Cross-Platform C/C   Program?

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!

Statement:
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