Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create file with filesystem C++ library

How to create a file with filesystem C++ library?

I know there are different ways to create a file but I am perticularily intrested with filesystem library.

like image 865
Vallabh Patade Avatar asked Apr 21 '16 16:04

Vallabh Patade


Video Answer


2 Answers

This code will create a folder and a txt file (+ adds some text into there)

#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;
}
like image 150
Nirvikalpa Samadhi Avatar answered Sep 24 '22 06:09

Nirvikalpa Samadhi


You can't create a file using std::experimental::filesystem (C++14) or std::filesystem (C++17). The library can manipulate the path (including the name) and the status (permission) of existing, regular files, but is not intended for manipulating their contents.

Though resize_file() can manipulate file contents by truncating or zero-fill, it does only work with files that are already existing. When passing a non-existing file as parameter p, it throws resize_file(p, n): invalid arguments: operation not permitted.

like image 20
Roi Danton Avatar answered Sep 21 '22 06:09

Roi Danton