
从C++17开始,标准库引入了 std::filesystem 模块,极大简化了文件和目录的跨平台操作。在此之前,开发者通常依赖操作系统原生API(如Windows的Win32 API或Linux的POSIX接口)或第三方库(如Boost.Filesystem),代码可移植性差。而 std::filesystem 提供了一套统一、简洁、类型安全的接口,支持Windows、Linux、macOS等主流平台。
要使用 std::filesystem,需满足以下条件:
在GCC、Clang和MSVC中,通常只需添加编译选项 -std=c++17 即可启用。
std::filesystem::path 是所有文件系统操作的核心类,用于表示路径,支持跨平台路径分隔符自动处理(Windows用反斜杠,Unix系用正斜杠/)。
立即学习“C++免费学习笔记(深入)”;
示例:
path p = "/home/user/documents"; // Linux path p2 = "C:\Users\John\Desktop"; // Windows path p3 = "folder/file.txt"; cout << p3.filename() << endl; // 输出: file.txt cout << p3.stem() << endl; // 输出: file cout << p3.extension() << endl; // 输出: .txt path combined = p / "report.pdf"; // 路径拼接,自动适配分隔符
通过 status 和 is_* 系列函数可判断路径类型和属性:
示例:
path p = "test.txt";
if (exists(p)) {
if (is_regular_file(p))
cout << "文件大小: " << file_size(p) << " 字节" << endl;
else if (is_directory(p))
cout << "这是一个目录" << endl;
} else {
cout << "路径不存在" << endl;
}
std::filesystem 提供了简洁的目录管理接口:
遍历目录使用 directory_iterator 或 recursive_directory_iterator:
// 遍历当前目录
for (const auto& entry : directory_iterator(".")) {
cout << entry.path() << endl;
}
// 递归遍历子目录
for (const auto& entry : recursive_directory_iterator("data")) {
if (entry.is_regular_file() && entry.path().extension() == ".txt")
cout << "找到文本文件: " << entry.path() << endl;
}
移动、重命名和复制文件也变得非常简单:
示例:
// 复制并允许覆盖
copy("a.txt", "backup/a.txt", copy_options::overwrite_existing);
// 重命名文件
rename("old_name.txt", "new_name.txt");
// 移动目录
rename("temp/", "archive/temp/");
基本上就这些。std::filesystem 让C++具备了现代语言应有的文件系统操作能力,无需再写平台相关的代码。只要编译环境支持C++17,就可以放心使用这套接口进行跨平台开发。注意在实际项目中捕获可能抛出的 filesystem_error 异常,以增强健壮性。不复杂但容易忽略。
以上就是C++如何跨平台操作文件和目录_C++17标准库std::filesystem的使用教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号