So if you want to use the actual \ character in a file name, you have to double it:
what you want | how you write it
--------------------------+------------------------------
C:\WINDOWS | "C:\\WINDOWS"
C:\WINDOWS\notepad.exe | "C:\\WINDOWS\\notepad.exe"
1 2 3 4 5 6 7 8 9
void write_file()
{
string ss = "C:\\";
string path = ss + "my_file.txt";
ifstream out(path.c_str());
out << "stuff";
// out.close(); // not needed, explanation below
}
Closing the out file stream isn't needed to be done manually unless you want to re-open out with a different file name right after.
This is because when the write_file() function ends ("returns") the destructor of out will be called, and it will automatically close the file stream.
It should be noted that all modern operating systems support using the forward slash instead of the backslash, even Windows. Backslashes are such a hassle that I recommend avoiding their use entirely.
Thanks people. You helped me write this piece that works.
1 2 3 4 5 6 7 8 9 10 11 12
ss = "C:\" //or what ever drive letter you want it to be
void write_file()
{
string ss;
std::string str;
str = ss + "drop.txt";
const char * c = str.c_str();
ofstream file_wr;
file_wr.open (c);
file_wr << "This is text.";
file_wr.close();
}