0%

C++17新特性:文件系统操作std::filesystem

  1. 读取文件夹
  2. 判断文件夹存在及创建

读取文件夹

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <filesystem>

int main()
{
std::filesystem::path dir("D:\\dir");

std::filesystem::directory_iterator list(dir);

try
{
for (auto& file : list)
{
std::cout << file << " ";
std::cout << std::filesystem::file_size(file.path()) << std::endl;
}
}
catch (const std::exception& e)
{
std::cout << e.what() << std::endl;
}

return 0;
}

判断文件夹存在及创建

std::filesystem::create_directory不递归创建,std::filesystem::create_directories递归创建

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <filesystem>

int main()
{
std::filesystem::path dir("D:\\dir\\dir1\\dir2");

if (!std::filesystem::exists(dir))
{
if (std::filesystem::create_directories(dir))
{
std::cout << "success" << std::endl;
}
else
{
std::cerr << "failure" << std::endl;
}
}

return 0;
}

还可以创建一些软硬链接:

image-20230307120100512