Relative file paths not working

<code>
#include <iostream>
#include <fstream>

int main() {
srand(time(NULL));
ofstream dumpFile;
dumpFile.open("test/testFileInFolder.txt");
dumpFile << "test text";
if (dumpFile.is_open())
return 1;
else {
dumpFile.close();
return 0;
}
}
</code>

Different sources give different information on how to format relative file paths, and I know it depends on the system (Windows 8 for me), but I can't seem to find a format that works. I've tried forward slashes, double back slashes, preceding the folder name with slashes, using full file paths, etc. Nothing seems to work. The only result that will work is a file name with no path, causing the file to be created directly into my project solution directory. I can work with that, it's just messy and I'd prefer to be able to sort into folders.

If it helps, I'm working in Visual Studio 2015. Does anyone have any solutions for this?
Maybe you're not starting in the directory you think you are. / is the separator, so that part is correct.

As an aside, don't open/close file streams. Remember that an fstream is an object, it knows how to open/close files, that's kinda the point of having it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <Window.h>
#include <fstream>
#include <iostream>

int main()
{
    char dir[512];
    GetCurrentDirectory(sizeof(dir), dir);
    std::cout << "pwd=\"" << dir << "\"" << std::endl;

    std::ofstream dumpFile("test/testFileInFolder.txt");
    if (dumpFile)
        std::cout << "log file opened ok" << std::endl;
    else
        std::clog << "failed to open log file" << std::endl;
}
It's not opening the file in any directory. It should just be the project directory by default, but for some reason it won't work even if I give a full file path.

Thanks for the second tip, though, I thought declaring open() was required! All the example code I've seen uses it.
Try this and see what error message you get.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <fstream>
#include <cstdio>

int main()
{
  std::ofstream dumpFile("test/testFileInFolder.txt");
  if (!dumpFile)
  {
    std::perror("Error opening file: ");
    return -1;
  }
  std::cout << "\nFile opend.\n";
}
It's not opening the file in any directory.
Does directory test exist?
Last edited on
Holy shit. Thank you, kbw, for making me feel like a dumbass.

If the file doesn't exist, it creates the file. I just assumed it would do the same for the /test/ folder. After creating one, it worked without issue. Thank you!
Thomas, issue was solved, but perror didn't do anything. Do you know where that's supposed to print in Visual Studio 2015?
Normally perror prints to stderr.
http://www.cplusplus.com/reference/cstdio/perror/
When I an it I got the following message:
Error opening file: : No such file or directory

Topic archived. No new replies allowed.