tags:

views:

570

answers:

3

Hey everyone!

I know this is rather laughable, but I can't seem to get simple C++ ofstream code to work. Can you please tell me what could possibly be wrong with the following code:

    #include <fstream>

    ...

    ofstream File("C:\temp.txt");

    if(File)
       File << "lolwtf";

Opening the ofstream fails whenever I specify an absolute path. Relative paths seems to work with no issues. I'm really uncertain as to what the issue is here.

+17  A: 

Your path is invalid:

"C:\temp.txt"

The \ is escaping the "t" as a horizontal tab character, so the path value ends up as:

"C:    emp.txt"

What you want is:

"C:\\temp.txt"

or

"C:/temp.txt"
James McNellis
I have done this mistake often in scripted languages and it comes back and says invalid path "blah" - with the escaped character disappearing immediately making me aware of the error.
whatnick
This is the issue. I was trying to get the Windows environment variable PATH, which was coming back with non-escaped slashes. Thanks!
ModeEngage
+4  A: 

The problem is in your string, you are not escaping the backslash.

 ofstream File("C:\\temp.txt");
Ed Swangren
@Ed: File isn't a pointer, but stream objects derived from basic_ios have an operator void*(), which returns a null pointer if fail() would return true, otherwise some non-null pointer is returned. This is how 'if(File)' works. (But you're right about having to escape the backslash.)
Steve Folly
Ahh, ok, thanks. I should have made sure of that before I posted.
Ed Swangren
+2  A: 

Even though Windows people seem to prefer the non-standard '\' character as a path separator, the standard '/' works perfectly and avoids annoying problems like this.

So, my advice is to stick to forward slashes...

std::ofstream File("C:/temp.txt");
alex tingle
non-standard? I wasn't aware that the path separator was standardized.
Ed Swangren
Name a platform in common use today where '/' is not a valid path separator. VMS maybe?
alex tingle