VS2017 C++ 还没有正式支持filesystem,命名空间是std::experimental::filesystem。
https://zh.cppreference.com/w/cpp/filesystem/copy_file
注意:copy_file(from, to, option) ,以下情况报错(crash):1)源文件不存在报错,2)目标文件不允许覆盖(option没设置覆盖属性)。
一些常用的方法:
#include <iostream>
#include <filesystem>
#include <fstream>
#include <string>
using namespace std;
int main() {
namespace fs = std::experimental::filesystem;
cout << "current path: is " << fs::current_path() << endl;
//to string
string s = fs::current_path().generic_string();
cout << s << endl;
fs::path p1("c:\\tmp\\hello.txt");
cout << "exists() = " << fs::exists(p1) << "\n"
<< "root_name() = " << p1.root_name() << "\n"
<< "root_path() = " << p1.root_path() << "\n"
<< "relative_path() = " << p1.relative_path() << "\n"
<< "parent_path() = " << p1.parent_path() << "\n"
<< "filename() = " << p1.filename() << "\n"
<< "stem() = " << p1.stem() << "\n"
<< "extension() = " << p1.extension() << "\n";
auto p2 = p1.replace_extension(".bak");
cout << "New filename: " << p2 << endl;
auto p3 = p1.parent_path() / p1.stem();
p3 += "_111.txt";
cout << "New filename: " << p3 << endl;
auto p = fs::current_path() / "1.txt";
std::ofstream(p).put('a'); // 创建文件大小为 1
std::cout << "File size = " << fs::file_size(p) << '\n';
fs::remove(p);
return 0;
}
/*输出
current path: is D:\git_clone\mycpp11\cpp11\test
D:/git_clone/mycpp11/cpp11/test
exists() = 0
root_name() = c:
root_path() = c:\
relative_path() = tmp\hello.txt
parent_path() = c:\tmp
filename() = hello.txt
stem() = hello
extension() = .txt
New filename: c:\tmp\hello.bak
New filename: c:\tmp\hello_111.txt
File size = 1
*/