判断文件是否存在
1
2
3
4
5
6
7
8
#include <fstream>

std::ifstream fin(file_name);
if (!fin) {
printf("file not exist");
return false;
}
fin.close();

C++17中有std::filesystem::path,相当于Boost的filesystem模块,只需要set(CMAKE_CXX_STANDARD 17)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <filesystem>
#include <iostream>
namespace fs = std::filesystem;


int main()
{
std::filesystem::path test_path("/home/user/test.yaml");
//判断路径是否存在
std::cout << "is_exist = " << std::filesystem::exists(test_path) << std::endl;

// 判断路径为绝对路径还是相对路径
std::cout << "is_abs = " << test_path.is_absolute() << std::endl;
std::cout << "is_relative = " << test_path.is_relative() << std::endl;
// 取得不带扩展名的文件名
std::cout << "stem = " << test_path.stem() << std::endl;
// 取得扩展名,如果没有,则为空
std::cout << "extension = " << test_path.extension() << std::endl;
// 取得文件名
std::cout << "filename = " << test_path.filename() << std::endl;

std::cout << "----------------------------------------" << std::endl;

std::filesystem::path test_dir("/home/user/Pictures");
//判断是文件还是文件夹
std::cout << "is_file = " << std::filesystem::is_regular_file(test_path) << std::endl;
std::cout << "is_dir = " << std::filesystem::is_directory(test_dir) << std::endl;

//关于路径拼接
std::filesystem::path new_path = test_dir / "test.txt";
std::cout << "new_path = " << new_path << std::endl;

//取得当前绝对工作路径 编译后可执行文件的路径文件夹
std::filesystem::path workPath = std::filesystem::current_path();
std::cout << "current exe path = " << workPath << std::endl;

//递归遍历指定路径下所有文件,文件夹名字也会返回
std::filesystem::recursive_directory_iterator iterDir(test_dir);
for (auto &it: iterDir)
{
//打印绝对路径
std::cout << it << std::endl;
// 不打印路径而是打印文件名
std::cout << it.path().filename() << std::endl;
}

//给一个相对路径,返回绝对路径
std::filesystem::path path_test("./");
std::cout << "abs_path = " << std::filesystem::absolute(path_test) << std::endl;


// 删除文件, 路径不存在不报错
// std::filesystem::remove(test_dir / "deepfakes"/"yolov7.pdf");

// 拷贝文件夹, 删除文件夹
// std::filesystem::copy(test_dir, test_dir.parent_path() / "works", std::filesystem::copy_options::recursive);
// std::filesystem::remove_all(test_dir.parent_path() / "works");
return 0;
}