path to output files

Good evening,

short question to writing output files.
Consider this example code from Stack Overflow:

1
2
3
4
5
6
7
#include <fstream>
#include <iostream>

int main()  {
    std::ofstream of( "C:\\mydir\\somewhere\\log.txt" );
    of << "hello\n";
}


Can I also use a relative path instead of this absolute path?

Suppose I have a folder A and it contains folder B1 and B2. My .exe runs in B1 but I want it to write my outputfile into B2. How would I code this?
Also, what happens if B2 does not exist during execution? Will it be created?

Regards!
Last edited on
My .exe runs in B1 but I want it to write my outputfile into B2. How would I code this?

You can use two methods, an absolute path, or a relative path.

std::ofstream of("C:\\mydir\\A\\B2\\log.txt"); // Absolute
std::ofstream of2(..\\B2\\log.txt"); // Relative

See https://docs.microsoft.com/en-us/windows/desktop/fileio/naming-a-file for more information on Windows file/path structures.

Also, what happens if B2 does not exist during execution? Will it be created?

If you try to open a file in a non-existing directory the open will fail and the file will not be created. An ofstream by itself doesn't know how to create a directory.


Thank you!

So if I use the relative path version, I need to make sure that there is a folder B2 at the specified relative position to the place from where I start my program.
Yes, no matter what method you try to use (absolute/relative) all the folders must exist.



Topic archived. No new replies allowed.