File paths

Oct 25, 2015 at 11:29pm
Hi, how do I figure out the current place the .exe file is in, create a folder in that place and then place files in that new folder? This is what I have:

1
2
mkdir("Files")
std::ofstream write(Files\"File.txt")


mkdir("Files") works fine (knowing how to create a folder with a relative and absolute path would be nice too), but how do I make it write into that folder? Thanks!
Oct 26, 2015 at 12:05am
For POSIX systems:
1
2
mkdir("Files");
std::ofstream write("Files/File.txt");


On Windows:
1
2
CreateDirectory("Files", NULL);
std::ofstream write("Files\\File.txt");


To do it "properly", check if there's a path component in argv[0] and apply the current directory to it. But in it's not worth going overboard with it as real programs are run from secure directories and their data is held somewhere else.
Last edited on Oct 26, 2015 at 12:12am
Oct 26, 2015 at 12:13am
What do I do if I don't have a continuous file name? I need to generate a random name for the file with a function that returns a string:

1
2
mkdir("Files");
std::ofstream write(genString() + ".txt");


EDIT: Figured it out, used a +:

1
2
CreateDirectory("Files", NULL);
std::ofstream write("Files\\" + genString() + ".txt");


Thank you for your help! One thing though, both methods you provided work on my Windows 7. Is that supposed to be the case? Also what you said about the proper way is way over my head, I have no idea what you meant.
Last edited on Oct 26, 2015 at 12:23am
Oct 26, 2015 at 3:39am
Well, it depends on how you run the program. Let's say the program is in D:\bin\ and you open a shell and go to D:\. Then you run the program as D:\bin\prog.exe.

The current directory is D:\ so your program will write it's output in D:\Files\, not in D:\bin\Files\. Anyway, that's the issue.
Oct 26, 2015 at 8:17am
Topic archived. No new replies allowed.