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 :用于删除文件或目录

一些常用功能示例

#include 
#include 

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;
}


你可能感兴趣的:(c++,算法,开发语言)