Can anyone help me with ifstream?

Mar 1, 2014 at 9:49am
what am i doing wrong? I am kinda new to c++ ,and i don't see what is wrong with this code. I am using Dev C++ 5.6.1.

1
2
3
4
5
6
7
8
 void write_file ()
{
string ss = "C:\"; 
string path = ss + "my_file.txt";
ifstream out(path.c_str());
out << "stuff";
out.close();
} 
Last edited on Mar 1, 2014 at 9:50am
Mar 1, 2014 at 10:11am
You need to escape the backslash in 'ss', by doing one of the following:

string ss = "C:\\";

string ss = R"(C:\)";
Last edited on Mar 1, 2014 at 10:12am
Mar 1, 2014 at 10:22am
In strings, the \ character has a special purpose: it denotes an escape sequence.
http://en.cppreference.com/w/cpp/language/escape

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.
Mar 1, 2014 at 4:20pm
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.
Mar 1, 2014 at 11:54pm
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();
}  
Mar 2, 2014 at 12:07am
As the syntax highlighting shows, you have a problem on line 1!
Mar 2, 2014 at 8:25am
Thanks people. You helped me write this piece that works.

Sarcasm, yes? You should learn to mark it.

So you're ignoring the advice to double the backslash, or to use forward slashes, or to not close the file streams, and then you forget a semicolon.

It's as if you never read anyone's reply at all. It's as if you're not here to learn. [/sarcasm]
Topic archived. No new replies allowed.