How to create a folder in C ++ without a path name, just the name of the folder you want to create?

Possible duplicate:
Creating a directory in C or C ++

I want to create a folder called "BobtheBuilder". And then I want to create a text file in it. I want to do this without being aware of my path. I do not want to enter:

ofstream out("C:/MyComputer/User/Jeff/etc/BobtheBuilder/NewFile.txt"); 

I want it to be local to this area, where my executable is contained as follows:

 ofstream out("/BobtheBuilder/NewFile.txt"); 

Is it possible? Should I know the entire path name for file management? I feel this is possible because you can create or open a file that is in the same directory as the program:

 ifstream inf("NewFile.txt"); 

Or there is a special keyword that fills the previous path as follows:

 ifstream inf("FILLIN/BobtheBuilder/NewFile.txt"); 

thanks

+4
source share
2 answers

You can absolutely specify a relative path, for example "BobtheBuilder / NewFile.txt", without specifying the entire path. However, you will need to create a folder in front of the file. Since creating folders is platform-specific, and since you are on Windows, you will need to call the CreateDirectory function with "BobtheBuilder" as its parameter. Then the folder will be created in the default working directory of the program, which is the same folder as the executable file. You can change this working directory using the SetCurrentDirectory function before creating the folder and file.

+3
source

To create a directory, you can use the C function:

 int mkdir(const char *pathname, mode_t mode); 

If you can use Boost then it will become easier and more C ++ friendly:

 bool create_directories(const path& p); // usage example boost::filesystem::create_directories("./BobtheBuilder"); 

As you mentioned in your question, you can use both absolute and relative paths. It depends on your intentions. In your case, you can simply do:

 boost::filesystem::create_directories("./BobtheBuilder"); ofstream out("./BobtheBuilder/NewFile.txt"); 

no need to specify an absolute path at all.

If you often need to manage your paths, Boost provides many useful traffic management tools. As an example, consider the problem that you mentioned in your question: you want to get the full path to the current directory, and then add the relative path. You can do this very easily:

  #include <boost/filesystem.hpp> namespace fs = boost::filesystem; ... fs::path curr_abs_path = fs::current_path(); fs::path rel_path = "foo/bar"; fs::path combined = (curr_abs_path /= rel_path); cout << combined << endl; 

Assuming the current directory is / tmp /, the previous code snippet will print:

/ Tmp / foo / bar

operator/= is responsible for adding two paths and returning a combined result.

0
source

Source: https://habr.com/ru/post/1414575/


All Articles