I can't open a file outside the project directory

I'm trying to open a text file on the root of my C drive, but it won't open it for some reason.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int main ( long argc, char *argv[] )
{
	ifstream file_in;
        file_in.open ( "C:\file.txt", ios::in);

        if (file_in.is_open())
        {
	   cout<<"open";
        }
        else
        {
	   cout<<"failed";
        }
	system ("pause");
	return 0;
}

It always fails, but if I change the path to "file.txt" and put it directly in the project folder then it loads.
Last edited on
try to change "C:\file.txt" to "C:/file.txt or "C:\\file.txt"
Last edited on
Thanks! That works, but now I'm having issues getting it to work if file.txt is on the desktop. This is what my path looks like:
C:\\Users\<MY NAME HERE>\Desktop\file.txt
EDIT:
It seems like changing all the backward slashes to double worked.
C:\\Users\\<MY NAME HERE>\\Desktop\\file.txt
The backwards slash in a string was probably confusing it.
.
Last edited on
Yes, that would do it. A backslash inside a string is interpreted as an escape for the subsequent character. If you want a backslash to be part of the actual string, you need to escape the backslash itself, i.e. a double backslash.
And Windows does understand forward slashes used in its API. So use forward slashes on all platforms.
Topic archived. No new replies allowed.