Please tell folder1\folder2\...\folderN best way to write a file to a folder folder1\folder2\...\folderN , if only folder1\folder2\...\folderM .

In this case, the recording is performed using std::ofstream .

It is clear that the problem can be solved head-on - parse the path to the file and check whether each folder exists in the path and if not, create it.

But maybe / probably there is a simpler way to solve this problem?

    1 answer 1

    I would do this — use the standard <filesystem> library and create a directory using create_directories() without looking at whether there is already such a directory or not. No - it will create, there is - well, well :)

    And then I would create a file.

    Anyway, checking the existence of a 100% guarantee does not give - between checking and creating a file, someone else can catalog and erase :)

    Update

     #include <iostream> #include <filesystem> int main(int argc, const char * argv[]) { std::error_code e; std::cout << std::filesystem::create_directories("G:\\Tmp\\Test\\aaa\\bbb\\ccc",e) << std::endl; std::cout << std::filesystem::create_directory("G:\\Tmp\\Test\\zzz",e) << std::endl; } 

    VC ++ 2017 15.9.7

    Compiled, works.

    • it seems like the studio is 2017, and it sees the library library and inside it, the necessary functions are inside this library, but still on std::filesystem::create_directory(path); swears, such as there is no such function in std :( - Zhihar
    • Check the spelling ... In response, added the code that I just compiled and executed. Works ... - Harry
    • @Zhihar Make sure the standard is set to C ++ 17 - VTT
    • @VVT, updated to 15.9.7 (it was 15.2), in the project settings I set Windows SDK Version 10.0.17763.0 - it did not help. Created a new project - all the same, it swears on the filesystem :( Maybe somewhere else you need to set C ++ 17? - Zhihar
    • /std:c++17 . Or /std:latest - Harry