这段代码将创建一个文件夹和一个txt文件(+在其中添加一些文本)
#include <iostream>
#include <filesystem>
#include <fstream>
int main()
{
std::filesystem::path path{ "C:\\TestingFolder" }; //creates TestingFolder object on C:
path /= "my new file.txt"; //put something into there
std::filesystem::create_directories(path.parent_path()); //add directories based on the object path (without this line it will not work)
std::ofstream ofs(path);
ofs << "this is some text in the new file\n";
ofs.close();
return 0;
}
不能使用std::experimental::filesystem
(C++14)或std::filesystem
(C++17)创建文件。该库可以操作现有常规文件的路径(包括名称)和状态(权限),但不用于操作其内容。
虽然resize_file()
可以通过截断或零填充操作文件内容,但它只能处理已经存在的文件。当将不存在的文件作为参数p
传递时,它将抛出resize_file(p,n):无效参数:不允许操作
。