一、获取磁盘空间
#include<iostream>
#include<filesystem>
int main()
{
using std::cout;
using std::endl;
namespace fs = std::filesystem;
//定义路径对象
fs::path p{ "C:\\" };
//展示磁盘的总大小和剩余大小
cout << "C:total space:" << fs::space(p).capacity << endl;
cout << "C:free space:" << fs::space(p).free << endl;
std::cin.get();
return 0;
}
结果如上图所示。
二、路径分解
#include<iostream>
#include<filesystem>
using std::cout;
using std::endl;
int main()
{
namespace fs = std::filesystem;
//定义路径p
fs::path p{ R"(E:\C_pp\hello.txt)" };
//是否存在?根名?根路径?相对路径?
if (p.empty())
{
cout << "Path" << p << "is empty." << endl;
}
if (!fs::exists(p))
{
cout << "Path" << p << "does not exist." << endl;
std::exit(0);
}
cout << "root_name(): " << p.root_name() << "\n"
<< "root_path():" << p.root_path() << "\n"
<< "relative_path():" << p.relative_path() << "\n";
//父路径?文件名?文件名主干?拓展名?
cout << "parent_path():" << p.parent_path() << "\n"
<< "filename():" << p.filename() << "\n"
<< "stem():" << p.stem() << "\n"
<< "extension():" << p.extension() << endl;
std::cin.get();
}
结果如上图所示。
三、特殊运算符
#include<iostream>
#include<filesystem>
using std::cout;
using std::endl;
namespace fs = std::filesystem;
int main()
{
fs::path p1{ R"(E:\C_pp)" };
fs::path p2{ R"(E:\C_pp)" };
fs::path p3{ " " };
//append和/= 会自动添加/
p1.append(R"(users)");
p1 /= R"(cyd)";
cout << p1 << endl;
//concat和+= 不会自动添加/ 因此输出结果不合法
p2.concat(R"(users)");
p2 += R"(cyd)";
cout << p2 << endl;
//用运算符/拼凑一个新路径
p3 = p3 / R"(C:temp)" / R"(users)" / R"(cyd)";
cout << p3 << endl;
std::cin.get();
}
结果如上图所示。