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.
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;
}
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With