C++ 获取当前路径 不能用getcwd
时间: 2023-07-16 21:17:35 浏览: 65
如果你的操作系统是 Windows,你可以使用 GetModuleFileName 函数获取当前程序的完整路径,然后从中提取出当前路径。
示例代码如下:
```cpp
#include <windows.h>
#include <iostream>
int main() {
char buffer[MAX_PATH];
GetModuleFileName(NULL, buffer, MAX_PATH);
std::string::size_type pos = std::string(buffer).find_last_of("\\/");
std::cout << std::string(buffer).substr(0, pos) << std::endl;
return 0;
}
```
如果你的操作系统是 Linux 或者 macOS,你可以使用 proc 文件系统获取当前进程的完整路径,然后从中提取出当前路径。
示例代码如下:
```cpp
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <limits.h>
#include <iostream>
int main() {
char buffer[PATH_MAX];
ssize_t len = ::readlink("/proc/self/exe", buffer, sizeof(buffer));
if (len != -1) {
buffer[len] = '\0';
std::string::size_type pos = std::string(buffer).find_last_of("\\/");
std::cout << std::string(buffer).substr(0, pos) << std::endl;
}
return 0;
}
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)