Home > Backend Development > C++ > How Can I Determine a Program's Running Directory on Windows and Linux?

How Can I Determine a Program's Running Directory on Windows and Linux?

Patricia Arquette
Release: 2024-12-21 15:45:09
Original
281 people have browsed it

How Can I Determine a Program's Running Directory on Windows and Linux?

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!

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