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
Release: 2024-12-21 02:48:12
Original
792 people have browsed it

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

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template