How to Search for a folder with std::filesystem

closed account (DEhqDjzh)
Hello I want to create a program that will search for a folder in the folder that exe is running. If here is a folder called user it will search for a file called currentuser.dat in that folder. If not then it will create that folder and create currentuser.dat file and write to it. I found some articles about using third party or windows functions but i dont want. How can i do that with std::filesystem
If not then it will create that folder

Sounds like you don't need to search at all, just go ahead and create that fonder. If it's already there, it won't do anything.

1
2
3
4
5
6
7
8
9
#include <fstream>
#include <filesystem>
namespace fs = std::filesystem;
int main()
{
    fs::path p = fs::current_path() / "user";
    fs::create_directory(p); 
    std::ofstream{p / "currentuser.dat"} << "stuff";
}

live demo https://wandbox.org/permlink/QtF36ztY1uMHcfiJ

Note there may be a file (not folder) called "user" in the current directory, in which case this little demo also quietly fails and does nothing.

(if you do want to search, the API to call is directory_iterator: https://en.cppreference.com/w/cpp/filesystem/directory_iterator ) but remember that result of any filesystem search is outdated the moment you look at it. The search will tell you there is no folder called "user", but by the time your program gets to the next line and attempts creating it, another program may have created it.
Last edited on
closed account (DEhqDjzh)
@Cubbi and how to create a folder in exe folder ? The code is creating folder in the source code folder ? (sorry for using word "folder" to much )
Last edited on
Actually that program is creating the "user" directory off the current working directory, so if the working directory is the directory where your .exe is located then "user" will be created where you expect it to be created.

When running the program from many IDE the current working directory will quite often be the directory containing the "project" files.

right, that program expects you ran it directly, not through IDE or with otherwise swapped current working directory. Picking up a stable place for user settings that don't depend on how you run he program is a little more work (on Windows I'd consider making a folder in C:\Users\yourname\AppData\Local)
Topic archived. No new replies allowed.