std::ofstream

May 5, 2015 at 8:11pm
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 May 5, 2015 at 8:14pm
May 5, 2015 at 8:48pm
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)
}
May 5, 2015 at 9:04pm
@Gamer2015
Just an FYI, you can use a forward slash as a path separator on Windows as well.
Last edited on May 5, 2015 at 9:08pm
May 6, 2015 at 2:02am
I experienced an error on line 4. I use windows
cpp.sh/6xrl
May 6, 2015 at 3:17am
You cannot concatenate cstrings with the + operator.
May 6, 2015 at 6:09am
Okay... So what do you suggest I do about this @naraku9333
May 6, 2015 at 7:06am
std::ofstream file("/path/to/file/filename.txt");
May 6, 2015 at 12:13pm
@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)
}


May 6, 2015 at 1:20pm
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.
May 7, 2015 at 12:15pm
Awesome!!! tnx guys
Topic archived. No new replies allowed.