C++17 std::filesystem

std::filesystem 是 C++17 标准引入的文件系统库,提供了一套用于处理文件和目录的 API。它主要包括以下几个核心类:

std::filesystem::path:用于表示文件系统路径。它提供了一系列方法,允许你对路径进行各种操作,如拼接、分解、获取文件名等。路径可以是相对路径或绝对路径,可以包含文件名、目录名等信息。
std::filesystem::directory_entry:用于表示目录中的一个条目,可以是文件或目录。你可以使用这个类来检查目录中的条目类型、获取条目路径等信息。
std::filesystem::directory_iterator :是一个用于遍历目录内容的迭代器。你可以使用它来遍历目录中的所有文件和子目录,并获取它们的信息。

std::filesystem::create_directory:用于创建目录
std::filesystem::remove :用于删除文件或目录

一些常用功能示例

cpp 复制代码
#include <iostream>
#include <filesystem>

namespace fs = std::filesystem;

int main() 
{
	// 构造路径
	fs::path currentPath = fs::current_path();
	fs::path filePath = currentPath / "example" / "test.txt";

	// 获取路径信息
	std::cout << "Current Path: " << currentPath << std::endl;
	std::cout << "File Path: " << filePath << std::endl;
	std::cout << "File Name: " << filePath.filename() << std::endl;
	std::cout << "Parent Path: " << filePath.parent_path() << std::endl;
	std::cout << "Root Path: " << filePath.root_path() << std::endl;
	std::cout << "Extension: " << filePath.extension() << std::endl;

	// 连接路径
	fs::path subdir = "subdirectory";
	fs::path combinedPath = filePath.parent_path() / subdir / filePath.filename();
	std::cout << "Combined Path: " << combinedPath << std::endl;

	// 迭代目录下该目录下所有文件的路径
	std::cout << "Contents of current directory:" << std::endl;
	for (const auto& entry : fs::directory_iterator(currentPath)) 
	{
		std::cout << entry.path() << std::endl;
	}

	// 检查路径是否存在
	std::cout << "File exists: " << fs::exists(filePath) << std::endl;
	
	// 文件更名
	fs::rename(filePath, filePath.parent_path() / "ttttt.txt");
	std::cout << "File Path: " << filePath << std::endl;


	return 0;
}
相关推荐
书到用时方恨少!9 分钟前
Python os 模块使用指南:系统交互的瑞士军刀
开发语言·python
我是大猴子10 分钟前
事务失效的几种情况以及是为什么(详解)
java·开发语言
不熬夜的熬润之11 分钟前
APCE-平均峰值相关能量
人工智能·算法·计算机视觉
yzx99101313 分钟前
实时数据流处理实战:从滑动窗口算法到Docker部署
算法·docker·容器
-许平安-17 分钟前
MCP项目笔记六(PluginsLoader)
c++·笔记·raii·plugin system
呜喵王阿尔萨斯19 分钟前
argc & argv
c语言·c++
Vect__26 分钟前
std::bind和lambda的使用
c++
她叫我大水龙34 分钟前
MSYS2的C/C++,python2,python3编译环境安装脚本
c语言·c++
佩奇大王35 分钟前
P674 三羊献瑞
算法·深度优先·图论
武藤一雄1 小时前
C#:nameof 运算符全指南
开发语言·microsoft·c#·.net·.netcore