C++中获取当前路径
时间: 2024-10-20 14:17:47 浏览: 22
C\C++ 获取当前路径实例详解
在C++中,获取当前路径的方法有多种,具体取决于你所使用的平台和编程环境。以下是一些常见的方法:
1. **使用 `<filesystem>` 库(C++17及更高版本)**:
```cpp
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
int main() {
fs::path current_path = fs::current_path();
std::cout << "Current path: " << current_path << std::endl;
return 0;
}
```
2. **使用 `getcwd` 函数(POSIX标准)**:
```cpp
#include <iostream>
#include <unistd.h>
int main() {
char buffer[FILENAME_MAX];
if (getcwd(buffer, sizeof(buffer)) != nullptr) {
std::cout << "Current path: " << buffer << std::endl;
} else {
perror("getcwd() error");
}
return 0;
}
```
3. **在Windows上使用 `GetCurrentDirectory` 函数**:
```cpp
#include <iostream>
#include <windows.h>
int main() {
char buffer[MAX_PATH];
if (GetCurrentDirectory(sizeof(buffer), buffer) != 0) {
std::cout << "Current path: " << buffer << std::endl;
} else {
std::cerr << "GetCurrentDirectory() error: " << GetLastError() << std::endl;
}
return 0;
}
```
4. **通过命令行参数获取执行路径**:
```cpp
#include <iostream>
int main(int argc, char* argv[]) {
if (argc > 0) {
std::cout << "Executable path: " << (argv[0]) << std::endl;
}
return 0;
}
```
5. **使用Boost库的 `boost::filesystem`**:
```cpp
#include <iostream>
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
int main() {
fs::path current_path = fs::current_path();
std::cout << "Current path: " << current_path << std::endl;
return 0;
}
```
阅读全文