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;
}
相关推荐
明志数科11 分钟前
人类视频与机器人示教的数据配比:分层训练的数据采购与采集设计
人工智能·算法
Wang's Blog18 分钟前
Java 项目实战: 交友项目 - 喜欢与取消喜欢
java·开发语言·交友
Ivanqhz23 分钟前
MoE 原理、TC/EC 路由、LSH-MoE 与负载均衡浅析
运维·网络·人工智能·深度学习·算法·机器学习·负载均衡
Sarvartha25 分钟前
栈的四则运算、栈的递归应用
数据结构·算法
stolentime32 分钟前
CF2277E Tree Guessing题解
c++·算法·贪心算法·交互·ad-hoc
逐光者9331 小时前
杨氏模量:从定义到工程应用
算法
quantdash_cc1 小时前
如何检查滚动收益率计算中的窗口长度不足?——从数学定义到 Pandas 实现
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
衍生星球1 小时前
【Java 语言】— 方法(方法定义、调用、参数、返回值、方法重载)
java·开发语言·方法
CodeGL1 小时前
16、Python Web开发
开发语言·前端·python
喵了几个咪1 小时前
GoWind UBA 拆解:把 Doris UNIQUE KEY 翻译成 ClickHouse——读数正确性对齐实录
开发语言·后端·clickhouse·微服务·golang·gowind