21xrx.com
2024-09-20 05:50:16 Friday
登录
文章检索 我的文章 写文章
如何在C++中获取程序运行的上一层路径
2023-06-27 20:28:57 深夜i     --     --
C++ 路径 获取 程序 上一层

在C++编程中,有时候需要获取程序运行所在的上一层路径(也就是程序所在目录的上一级目录)。本文将介绍一种常用的获取程序运行的上一层路径的方法。

方法步骤如下:

Step 1:包含头文件

需要使用 头文件中的GetCurrentDirectory函数,所以需要先包含该头文件。代码如下:

#include

Step 2:获取程序所在的路径

使用GetCurrentDirectory函数来获取程序所在的完整路径(包括程序自身文件名),代码如下:

char path[MAX_PATH];

GetCurrentDirectory(MAX_PATH, path);

Step 3:获取上一层路径

上一层路径就是从完整路径中去除程序自身文件名后的部分。可以使用string中的find_last_of和substr函数来实现,代码如下:

string strPath = path;

int pos = strPath.find_last_of('\\');

string strParentPath = strPath.substr(0, pos);

Step 4:输出上一层路径

获取到上一层路径后,可以直接打印输出,也可以进行其他操作。这里直接输出上一层路径,代码如下:

cout << strParentPath;

完整代码如下:

#include

#include

#include

using namespace std;

int main()

{

  char path[MAX_PATH];

  GetCurrentDirectory(MAX_PATH, path);

  string strPath = path;

  int pos = strPath.find_last_of('\\');

  string strParentPath = strPath.substr(0, pos);

  cout << strParentPath;

  return 0;

}

以上就是在C++中获取程序运行的上一层路径的方法,期望能够帮助到大家。

  
  
下一篇: Node.js异常处理

评论区

{{item['qq_nickname']}}
()
回复
回复