标准库标头 <filesystem> (C++17)学习

2024-09-07 20:52

本文主要是介绍标准库标头 <filesystem> (C++17)学习,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

此头文件是文件系统支持库的一部分。本篇介绍filesystem命名空间的一些函数。

函数

在命名空间 std::filesystem 定义

absolute

(C++17)

组成一个绝对路径
(函数)

canonicalweakly_canonical

(C++17)

组成一个规范路径
(函数)

relativeproximate

(C++17)

组成一个相对路径
(函数)

copy

(C++17)

复制文件或目录
(函数)

copy_file

(C++17)

复制文件内容
(函数)

copy_symlink

(C++17)

复制一个符号链接
(函数)

create_directorycreate_directories

(C++17)(C++17)

创建新目录
(函数)

create_hard_link

(C++17)

创建一个硬链接
(函数)

create_symlinkcreate_directory_symlink

(C++17)(C++17)

创建一个符号链接
(函数)

current_path

(C++17)

返回或设置当前工作目录
(函数)

exists

(C++17)

检查路径是否指代既存的文件系统对象
(函数)

equivalent

(C++17)

检查两个路径是否指代同一文件系统对象
(函数)

file_size

(C++17)

返回文件的大小
(函数)

hard_link_count

(C++17)

返回指代特定文件的硬链接数
(函数)

last_write_time

(C++17)

获取或设置最近一次数据修改的时间
(函数)

permissions

(C++17)

修改文件访问权限
(函数)

read_symlink

(C++17)

获得符号链接的目标
(函数)

removeremove_all

(C++17)(C++17)

移除一个文件或空目录
移除一个文件或递归地移除一个目录及其所有内容
(函数)

rename

(C++17)

移动或重命名一个文件或目录
(函数)

resize_file

(C++17)

以截断或填充零更改一个常规文件的大小
(函数)

space

(C++17)

确定文件系统上的可用空闲空间
(函数)

statussymlink_status

(C++17)(C++17)

确定文件属性
确定文件属性,检查符号链接目标
(函数)

temp_directory_path

(C++17)

返回一个适用于临时文件的目录
(函数)

 示例代码:

#include <filesystem>
#include <iostream>
#include <string>
#include <cstdlib>
#include <fstream>
#include <cstdint>
#include <system_error>namespace fs = std::filesystem;void show(std::filesystem::path x, std::filesystem::path y)
{std::cout << "x:\t\t " << x << "\ny:\t\t " << y << '\n'<< "relative(x, y):  "<< std::filesystem::relative(x, y) << '\n'<< "proximate(x, y): "<< std::filesystem::proximate(x, y) << "\n\n";
}void demo_exists(const fs::path& p, fs::file_status s = fs::file_status{})
{std::cout << p;if (fs::status_known(s) ? fs::exists(s) : fs::exists(p))std::cout << " exists\n";elsestd::cout << " does not exist\n";
}struct HumanReadable
{std::uintmax_t size{};private:friend std::ostream& operator<<(std::ostream& os, HumanReadable hr){int o{};double mantissa = hr.size;for (; mantissa >= 1024.; mantissa /= 1024., ++o);os << std::ceil(mantissa * 10.) / 10. << "BKMGTPE"[o];return o ? os << "B (" << hr.size << ')' : os;}
};int main(int, char const* argv[])
{//path current_path example  返回或设置当前工作目录 std::cout << "当前路径为 " << fs::current_path() << '\n';//path temp_directory_path example 返回一个适用于临时文件的目录 std::cout << "temp_directory_path " << fs::temp_directory_path() << '\n';//absolute example  当前路径/foo.c  组成一个绝对路径 std::filesystem::path p = "foo.c";std::cout << p << " 的绝对路径为 " << fs::absolute(p) << '\n';// create_directory/create_directories example 创建新目录 auto temp = fs::current_path();auto dir1 = temp / "abc";auto dir2 = temp / "abb/c2/e";std::filesystem::create_directory(dir1); //只能创建单个目录std::filesystem::create_directories(dir2);//可以创建多级目录std::filesystem::current_path(dir2);//设置当前路径// canonical/weakly_canonical  example 组成一个规范路径//"D:\\vscpp\\cpp20\\cpp20standard\\filesystem"auto p1 = std::filesystem::path("../../c2/./e");auto p2 = std::filesystem::path("../no-such-file");std::cout << "当前路径为 "<< std::filesystem::current_path() << '\n'<< p1 << " 的规范路径为 "<< std::filesystem::canonical(p1) << '\n'<< p2 << " 的弱规范路径为 "<< std::filesystem::weakly_canonical(p2) << '\n';try{[[maybe_unused]] auto x_x = std::filesystem::canonical(p2);// 不会抵达此处}catch (const std::exception& ex){std::cout << p2 << " 的规范路径抛出了异常:\n"<< ex.what() << '\n';}//relative / proximate 组成一个相对路径 show("/a/b/c", "/a/b");show("/a/c", "/a/b");show("c", "/a/b");show("/a/b", "c");//auto temp = fs::current_path();auto dir3 = temp / "abb\\c2";auto dir4 = temp / "abb\\dir4";auto file1 = temp / "abb\\file1.txt";auto file2 = temp / "abb\\file2.txt";std::cout << "dir3======================" << dir3 << "\n";std::ofstream(file1).put('a');fs::copy(file1, file2); // 复制文件fs::copy(dir3, dir4); // 复制目录(非递归)const auto copyOptions = fs::copy_options::update_existing| fs::copy_options::recursive| fs::copy_options::directories_only;auto dirAbc = temp / "abc";auto dir5 = temp / "abb_copy";fs::copy(dirAbc, dir5, copyOptions);static_cast<void>(std::system("tree"));// remove/remove_all 移除一个文件或空目录 / 移除一个文件或递归地移除一个目录及其所有内容fs::remove(file1);fs::remove(file2);fs::remove_all(dirAbc);fs::remove_all(dir5);//exists example 检查路径是否指代既存的文件系统对象 const fs::path sandbox{ temp/"sandbox" };fs::create_directory(sandbox);std::ofstream{ sandbox / "file" }; // 创建常规文件//fs::create_symlink("non-existing", sandbox / "symlink");demo_exists(sandbox);for (const auto& entry : fs::directory_iterator(sandbox))demo_exists(entry, entry.status()); // 使用来自 directory_entry 的缓存状态fs::remove_all(sandbox);// 硬链接等价  equivalent example 检查两个路径是否指代同一文件系统对象 fs::path path1 = ".";fs::path path2 = fs::current_path();if (fs::equivalent(path1, path2))std::cout << path1 << " is equivalent to " << path2 << '\n';// 符号链接等价 for (const fs::path lib : {"/lib/libc.so.6", "/lib/x86_64-linux-gnu/libc.so.6"}){try{path2 = lib.parent_path() / fs::read_symlink(lib);}catch (std::filesystem::filesystem_error const& ex){std::cout << ex.what() << '\n';continue;}if (fs::equivalent(lib, path2))std::cout << lib << " is equivalent to " << path2 << '\n';}//file_size example 返回文件的大小 fs::path example = "bug.nc";fs::path path3 = fs::current_path() / example;std::ofstream(path3).put('a'); // 创建大小为 1 的文件std::cout << example << " size = " << fs::file_size(path3) << '\n';fs::remove(path3);path3 = argv[0];std::cout << path3 << " size = " << HumanReadable{ fs::file_size(path3) } << '\n';try{std::cout << "尝试获取目录的大小:\n";[[maybe_unused]] auto x_x = fs::file_size("/dev");}catch (fs::filesystem_error& e){std::cout << e.what() << '\n';}for (std::error_code ec; fs::path bin : {"cat", "mouse"}){bin = "/bin" / bin;if (const std::uintmax_t size = fs::file_size(bin, ec); ec)std::cout << bin << " : " << ec.message() << '\n';elsestd::cout << bin << " size = " << HumanReadable{ size } << '\n';}//rename example 移动或重命名一个文件或目录 std::filesystem::path path4 = std::filesystem::current_path() / "sandbox";std::filesystem::create_directories(path4 / "from");std::ofstream{ path4 / "from/file1.txt" }.put('a');std::filesystem::create_directory(path4 / "to");fs::rename(path4 / "from/file1.txt", path4 / "to/file2.txt"); // OK
//	fs::rename(path4 / "from", path4 / "to/subdir"); // OK//space example确定文件系统上的可用空闲空间std::error_code ec;const std::filesystem::space_info si = std::filesystem::space(path4, ec);std::cout << "capacity: " << si.capacity << "\tavailable:" << si.available << "\tfree:" << si.free << '\n';//std::filesystem::remove_all(path4);std::cout << "hello world\n";return 0;
}

运行结果:

参考:

标准库标头 <filesystem> (C++17) - cppreference.com

这篇关于标准库标头 <filesystem> (C++17)学习的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1146134

相关文章

HarmonyOS学习(七)——UI(五)常用布局总结

自适应布局 1.1、线性布局(LinearLayout) 通过线性容器Row和Column实现线性布局。Column容器内的子组件按照垂直方向排列,Row组件中的子组件按照水平方向排列。 属性说明space通过space参数设置主轴上子组件的间距,达到各子组件在排列上的等间距效果alignItems设置子组件在交叉轴上的对齐方式,且在各类尺寸屏幕上表现一致,其中交叉轴为垂直时,取值为Vert

Ilya-AI分享的他在OpenAI学习到的15个提示工程技巧

Ilya(不是本人,claude AI)在社交媒体上分享了他在OpenAI学习到的15个Prompt撰写技巧。 以下是详细的内容: 提示精确化:在编写提示时,力求表达清晰准确。清楚地阐述任务需求和概念定义至关重要。例:不用"分析文本",而用"判断这段话的情感倾向:积极、消极还是中性"。 快速迭代:善于快速连续调整提示。熟练的提示工程师能够灵活地进行多轮优化。例:从"总结文章"到"用

【前端学习】AntV G6-08 深入图形与图形分组、自定义节点、节点动画(下)

【课程链接】 AntV G6:深入图形与图形分组、自定义节点、节点动画(下)_哔哩哔哩_bilibili 本章十吾老师讲解了一个复杂的自定义节点中,应该怎样去计算和绘制图形,如何给一个图形制作不间断的动画,以及在鼠标事件之后产生动画。(有点难,需要好好理解) <!DOCTYPE html><html><head><meta charset="UTF-8"><title>06

学习hash总结

2014/1/29/   最近刚开始学hash,名字很陌生,但是hash的思想却很熟悉,以前早就做过此类的题,但是不知道这就是hash思想而已,说白了hash就是一个映射,往往灵活利用数组的下标来实现算法,hash的作用:1、判重;2、统计次数;

【C++ Primer Plus习题】13.4

大家好,这里是国中之林! ❥前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站。有兴趣的可以点点进去看看← 问题: 解答: main.cpp #include <iostream>#include "port.h"int main() {Port p1;Port p2("Abc", "Bcc", 30);std::cout <<

C++包装器

包装器 在 C++ 中,“包装器”通常指的是一种设计模式或编程技巧,用于封装其他代码或对象,使其更易于使用、管理或扩展。包装器的概念在编程中非常普遍,可以用于函数、类、库等多个方面。下面是几个常见的 “包装器” 类型: 1. 函数包装器 函数包装器用于封装一个或多个函数,使其接口更统一或更便于调用。例如,std::function 是一个通用的函数包装器,它可以存储任意可调用对象(函数、函数

C++11第三弹:lambda表达式 | 新的类功能 | 模板的可变参数

🌈个人主页: 南桥几晴秋 🌈C++专栏: 南桥谈C++ 🌈C语言专栏: C语言学习系列 🌈Linux学习专栏: 南桥谈Linux 🌈数据结构学习专栏: 数据结构杂谈 🌈数据库学习专栏: 南桥谈MySQL 🌈Qt学习专栏: 南桥谈Qt 🌈菜鸡代码练习: 练习随想记录 🌈git学习: 南桥谈Git 🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈�

【C++】_list常用方法解析及模拟实现

相信自己的力量,只要对自己始终保持信心,尽自己最大努力去完成任何事,就算事情最终结果是失败了,努力了也不留遗憾。💓💓💓 目录   ✨说在前面 🍋知识点一:什么是list? •🌰1.list的定义 •🌰2.list的基本特性 •🌰3.常用接口介绍 🍋知识点二:list常用接口 •🌰1.默认成员函数 🔥构造函数(⭐) 🔥析构函数 •🌰2.list对象

06 C++Lambda表达式

lambda表达式的定义 没有显式模版形参的lambda表达式 [捕获] 前属性 (形参列表) 说明符 异常 后属性 尾随类型 约束 {函数体} 有显式模版形参的lambda表达式 [捕获] <模版形参> 模版约束 前属性 (形参列表) 说明符 异常 后属性 尾随类型 约束 {函数体} 含义 捕获:包含零个或者多个捕获符的逗号分隔列表 模板形参:用于泛型lambda提供个模板形参的名

零基础学习Redis(10) -- zset类型命令使用

zset是有序集合,内部除了存储元素外,还会存储一个score,存储在zset中的元素会按照score的大小升序排列,不同元素的score可以重复,score相同的元素会按照元素的字典序排列。 1. zset常用命令 1.1 zadd  zadd key [NX | XX] [GT | LT]   [CH] [INCR] score member [score member ...]