21xrx.com
2025-03-26 14:11:32 Wednesday
文章检索 我的文章 写文章
C++如何获取当前程序路径
2023-06-29 19:33:31 深夜i     --     --
C++ 获取 当前程序路径

在C++编程中,有时候我们需要获取当前程序的代码文件所在路径,这个路径信息可以用于程序运行时读取配置文件、读取其他资源文件等。本文将介绍两种C++获取当前程序路径的方法。

方法一:使用GetCurrentDirectory函数

GetCurrentDirectory函数可以获得当前工作目录的完整路径,如果我们在程序启动时首先将当前工作目录设置为程序所在路径,那么这个函数就可以返回程序所在路径。具体的实现代码如下:

#include <iostream>
#include <Windows.h>
int main(int argc, char* argv[])
{
  char buffer[MAX_PATH];
  GetModuleFileName(NULL, buffer, MAX_PATH);
  
  std::string::size_type pos = std::string(buffer).find_last_of("\\/");
  std::string currentPath = std::string(buffer).substr(0, pos);
  std::cout << "当前程序路径为:" << currentPath << std::endl;
  return 0;
}

上述代码中通过调用GetModuleFileName函数获取当前程序的路径,然后在路径字符串中去掉文件名就得到了程序所在准确路径。

方法二:使用argv[0]参数

在Windows平台下,命令行下运行的一个可执行程序,在argv[0]参数中包含了完整的程序路径。只需要通过字符串处理把程序路径分离出来就行了。具体的实现代码如下:

#include <iostream>
int main(int argc, char* argv[])
{
  std::string fullPath = argv[0];
  std::string::size_type pos = std::string(fullPath).find_last_of("\\/");
  std::string currentPath = std::string(fullPath).substr(0, pos);
  std::cout << "当前程序路径为:" << currentPath << std::endl;
  return 0;
}

上述代码中,在main函数中通过读取argv[0]参数来获取当前程序的路径,通过字符串处理去掉文件名就得到了程序所在准确路径。

通过上面两种方法,我们可以轻松获取C++程序的当前路径。当然,如果需要在其他操作系统上获取程序路径,需要使用不同的API函数或者其他对应操作系统的命令。

  
  

评论区