文章目录
头文件:#include <filesystem>
命令空间:using namespace std::filesystem;
语法
完整文件名,文件名称,扩展名,父目录
- 输出路径中的文件名,即最后一位的
字符串中的路径要是"D:\\wang\\code\\qwe.txt"或者"D:/wang/code/qwe.txt"
std::string path = "D:/wang/code/qwe.txt";
std::filesystem::path file(path);
// 完整文件名
std::string fullFileName = file.filename().string();
// 获取文件名但不包括扩展名
std::string fileName = file.filename().stem().string();
// 获取文件扩展名,扩展名包含.这个符号
std::string fileExtensionName = file.extension().string();
std::cout << fullFileName << std::endl; // qwe.txt
std::cout << fileName << std::endl; // qwe
std::cout << fileExtensionName << std::endl; // .txt
// 父目录
std::filesystem::path parentPath = file.parent_path();
判断,是否存在,是否为(文件,目录,符号链接)
#include <iostream>
#include <filesystem>
int main()
{
std::filesystem::path path_to_check = "path/to/your/file_or_directory";
// 检查路径是否存在
if (std::filesystem::exists(path_to_check))
{
std::cout << "Path exists." << std::endl;
// 检查路径是否为目录
if (std::filesystem::is_directory(path_to_check))
{
std::cout << "It is a directory." << std::endl;
}
// 检查路径是否为文件
else if (std::filesystem::is_regular_file(path_to_check))
{
std::cout << "It is a regular file." << std::endl;
}
// 检查路径是否为符号链接
else if (std::filesystem::is_symlink(path_to_check))
{
std::cout << "It is a symbolic link." << std::endl;
}
// 其他类型的文件系统条目
else
{
std::cout << "It is some other type of filesystem entry." << std::endl;
}
}
else
{
std::cout << "Path does not exist." << std::endl;
}
return 0;
}
重命名/ 移动
文件重命名
#include <iostream>
#include <filesystem>
int main() {
std::filesystem::path old_filepath = "oldname.txt";
std::filesystem::path new_filepath = "newname.txt";
if (std::filesystem::exists(old_filepath))
{
if (std::filesystem::rename(old_filepath, new_filepath))
{
std::cout << "File renamed successfully." << std::endl;
} else
{
std::cout << "Failed to rename the file." << std::endl;
}
} else {
std::cout << "The file does not exist." << std::endl;
}
return 0;
}
目录重命名
#include <iostream>
#include <filesystem>
int main()
{
std::filesystem::path old_dirpath = "old_directory";
std::filesystem::path new_dirpath = "new_directory";
if (std::filesystem::exists(old_dirpath) && std::filesystem::is_directory(old_dirpath))
{
std::error_code ec; // 错误码,用于处理错误
std::filesystem::rename(old_dirpath, new_dirpath

本文介绍C++标准库中的filesystem库,涵盖文件与目录的基本操作,包括路径解析、文件重命名、目录创建与删除等功能,并提供实用代码示例。
最低0.47元/天 解锁文章
3268





