开发者

Unable to open fstream when specifying an absolute path

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.


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"


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");


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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜