vs2017 C++获取运行目录路径
时间: 2023-08-12 07:43:45 浏览: 136
在 Visual Studio 2017 中,你可以通过以下代码获取 C++ 程序运行时的目录路径:
```cpp
#include <iostream>
#include <Windows.h>
using namespace std;
int main()
{
char path[MAX_PATH];
GetModuleFileName(NULL, path, MAX_PATH);
string::size_type pos = string(path).find_last_of("\\/");
cout << "当前程序运行目录:" << string(path).substr(0, pos) << endl;
return 0;
}
```
其中 `GetModuleFileName()` 函数可以获取当前程序的文件路径,然后由于文件路径与程序运行时的目录路径不同,需要对文件路径进行处理,得到程序运行时的目录路径。
这里使用 `string::find_last_of()` 函数查找最后一个目录分隔符,然后使用 `string::substr()` 函数截取字符串,得到程序运行时的目录路径。最后输出即可。
需要注意的是,这里使用了 Windows.h 头文件,因为 Visual Studio 2017 是在 Windows 系统下运行的。如果你使用的是其他操作系统,可能需要使用不同的库或函数来获取程序运行时的目录路径。
相关问题
c++获取运行目录路径
你可以通过以下代码获取C++程序运行时的目录路径:
```cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
using namespace std;
int main()
{
char buf[1024];
getcwd(buf, 1024);
cout << "当前程序运行目录:" << buf << endl;
return 0;
}
```
其中 `getcwd` 函数可以获取当前工作目录的路径,即程序运行时的目录路径。
linux c++ 获取程序运行路径 不包括程序名称
在Linux C++中,可以通过获取程序运行时的完整路径,再通过处理字符串来获取程序运行路径,不包括程序名称。可以使用以下代码实现:
```c++
#include <iostream>
#include <unistd.h>
#include <limits.h>
int main()
{
char buffer[PATH_MAX];
ssize_t len = readlink("/proc/self/exe", buffer, sizeof(buffer)-1);
if (len != -1)
{
buffer[len] = '\0';
std::string path(buffer);
std::string::size_type pos = path.find_last_of('/');
if (pos != std::string::npos)
{
path = path.substr(0, pos+1);
std::cout << "The program is running in the directory: " << path << std::endl;
}
}
return 0;
}
```
该程序通过读取 `/proc/self/exe` 符号链接获取程序的完整路径,并通过查找最后一个 `/` 字符来获取程序运行路径,不包括程序名称。