使用文件系统 C++ 库创建文件

Val*_*ade 12 c++ filesystems

如何使用文件系统 C++ 库创建文件?

我知道有不同的方法来创建文件,但我对文件系统库特别感兴趣。

Roi*_*ton 16

您无法使用std::experimental::filesystem(C++14) 或std::filesystem(C++17) 创建文件。该库可以操作现有常规文件的路径(包括名称)和状态(权限),但不适用于操作其内容。

虽然resize_file()可以通过截断或零填充来操作文件内容,但它只适用于已经存在的文件。当传递一个不存在的文件作为参数时p,它会抛出resize_file(p, n): invalid arguments: operation not permitted.

  • 我喜欢答案只是回答了问题,但又填写了细微差别,这样就可以清楚地知道该功能以何种方式不受支持。我用它来证实我的发现。 (3认同)

Nir*_*dhi 12

此代码将创建一个文件夹和一个 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;
}
Run Code Online (Sandbox Code Playgroud)

  • 这使用 `std::ofstream` 来创建一个文件。`std::filesystem::path` 此处仅用于检索路径而不用于创建文件。 (2认同)