Home > Backend Development > C++ > How Can I Get a Program's Directory in C/C Across Different Platforms?

How Can I Get a Program's Directory in C/C Across Different Platforms?

Patricia Arquette
Release: 2024-12-22 17:03:10
Original
800 people have browsed it

How Can I Get a Program's Directory in C/C   Across Different Platforms?

Obtaining the Program's Directory in C/C Across Platforms and File Systems

In many scenarios, it becomes necessary to determine the directory from which a program is running. This information can be valuable for various purposes, such as accessing configuration files or logging. However, obtaining this directory in a platform-agnostic and filesystem-agnostic manner can pose a challenge.

Standard Approaches

The standard C/C library, unfortunately, does not provide a standard function for this purpose. For platform-specific solutions, the situation is as follows:

Windows

On Windows systems, the GetModuleFileName function can be used to retrieve the full path to the executing application.

char pBuf[256];
size_t len = sizeof(pBuf);
int bytes = GetModuleFileName(NULL, pBuf, len);
return bytes ? bytes : -1;
Copy after login

Linux

For Linux systems, the readlink function can be utilized to read the symbolic link pointing to the executing program.

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

The above is the detailed content of How Can I Get a Program's Directory in C/C 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