C++ filesystem
时间: 2024-01-14 09:02:04 浏览: 30
C++17引入了新的标准库文件系统头文件<filesystem>,它提供了一组用于管理计算机上文件和目录的类和函数。这个头文件中提供的类和函数可以让你轻松地创建、删除、移动、重命名和遍历文件和目录。
下面是一些常用的<filesystem>库函数和类:
- `std::filesystem::path`: 用于处理文件路径的类。
- `std::filesystem::directory_iterator`: 用于遍历目录的迭代器类。
- `std::filesystem::create_directory()`: 创建一个新目录。
- `std::filesystem::remove()`: 删除一个文件或目录。
- `std::filesystem::rename()`: 重命名一个文件或目录。
- `std::filesystem::copy()`: 复制一个文件或目录。
- `std::filesystem::exists()`: 检查文件或目录是否存在。
- `std::filesystem::is_directory()`: 检查给定路径是否是目录。
- `std::filesystem::is_regular_file()`: 检查给定路径是否是普通文件。
使用<filesystem>库可以方便地在C++程序中进行文件和目录操作,大大简化了与文件系统交互的过程。
相关问题
C++ filesystem 取后三项
你可以使用`std::filesystem::path`类的`std::distance`和`std::prev`函数来获取路径中的后三项。具体来说,你可以使用`std::distance`函数计算路径中元素的个数,并使用`std::prev`函数获取路径中从末尾开始数的前三个元素。以下是示例代码:
```c++
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
int main() {
std::string path_str = "/usr/local/bin";
fs::path p(path_str);
// 获取后三个元素
auto it = std::prev(p.end(), 3);
for (; it != p.end(); ++it) {
std::cout << *it << std::endl;
}
return 0;
}
```
在上面的代码中,首先将路径字符串`"/usr/local/bin"`转换为`std::filesystem::path`类型的对象`p`。然后,使用`std::prev(p.end(), 3)`获取从末尾开始数的前三个元素的迭代器,最终使用循环输出了后三个元素`"local"`、`"bin"`和空字符串。注意,路径中的最后一个元素可能是空字符串,因此在使用时需要进行判断。
c++filesystem中path转string
可以使用`c++`标准库`std::filesystem`中的`std::filesystem::path::string()`函数,将`path`对象转化为`string`类型。示例如下:
```cpp
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
int main() {
fs::path p = "example.txt";
std::string str = p.string();
std::cout << "Path: " << p << std::endl;
std::cout << "String: " << str << std::endl;
return 0;
}
```
输出结果为:
```
Path: "example.txt"
String: "example.txt"
```
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.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)