std::ofstream

Hi..
can I specify a location to save my file using ofstream?
e.g.

std::ofstream SAVEFILE ("filename.txt");// 'filename.txt' will be saved in my cpp files directory. My question is can I specify a different directory??
Last edited on
sure, you can write a relative and an absolute path, whatever you want.
notice that you'll have to make sure you use the right slash (backslash for directories in windows, forwardslash for unix based systems)

I'll use a define for the slash in this example because I don't know if you use linux or windows.
Note: to have 1 backslash you need 2 backslashes (1 for escaping the other one)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

#if defined(_WIN16) | defined(_WIN32) | defined(_WIN64)
#define SEPERATOR "\\"
#else
#define SEPERATOR "/"
#endif

int main()
{
    // std::ofstream file("Test" + SEPERATOR + "file.txt"); // create file in Folder Test/
    // std::ofstream file(".." + SEPERATOR + "file.txt") // create file in Parent folder
    // std::ofstream file("C:" + SEPERATOR + "file.txt") // create file in C: (only windows)
    // std::ofstream file("~" + SEPERATOR + "file.txt") // create file in home directory (only unix)
}
@Gamer2015
Just an FYI, you can use a forward slash as a path separator on Windows as well.
Last edited on
I experienced an error on line 4. I use windows
cpp.sh/6xrl
You cannot concatenate cstrings with the + operator.
Okay... So what do you suggest I do about this @naraku9333
std::ofstream file("/path/to/file/filename.txt");
@Gamer2015
Just an FYI, you can use a forward slash as a path separator on Windows as well.

Holy shit, I've never been so wrong in my whole life!
Thank you .__.

1
2
3
4
5
6
7
int main()
{
  std::ofstream file0("Test/file.txt") // creates file in Folder Test/ if Test/ exists!
  std::ofstream file1("../file.txt") // creates file in parent folder.
  std::ofstream file2("C:/file.txt") // creates file in C:/ (windows)
  std::ofstream file3("~/file.txt") // creates file in home-folder (linux)
}


Gamer2015 wrote:
 
std::ofstream file3("~/file.txt") // creates file in home-folder (linux) 

The tilde (~) is usually expanded by the shell, but the shell is not involved here so it will not work. If you have a directory named "~" in the current working directory it will create the file there.
Awesome!!! tnx guys
Topic archived. No new replies allowed.