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

How Can I Get a C/C Program's Execution Directory Cross-Platform?

Patricia Arquette
Release: 2025-01-04 00:54:39
Original
987 people have browsed it

How Can I Get a C/C   Program's Execution Directory Cross-Platform?

Obtaining Program's Running Directory in C/C

Problem:

Determining the full path of the directory where a program executes is a fundamental task in many programming scenarios. However, achieving this across various platforms and file systems can be challenging due to system-specific implementations. Can you provide a concise and efficient method to accomplish this platform-agnostically?

Solution:

Depending on the operating system, there are distinct approaches to retrieve this information:

Windows:

#include <windows.h>

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

Linux:

#include <string.h>
#include <unistd.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] = '';
  return bytes;
}
Copy after login

These methods rely on low-level system functions to obtain the path directly from the operating system, ensuring platform-agnostic functionality.

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