Open file by its full path in C++

Greg picture Greg · May 9, 2009 · Viewed 186.4k times · Source

I want the user to give me the full path where the file exists and not just the file name. How do I open the file this way?

Is it something like this:

ifstream file;
file.open("C:/Demo.txt", ios::in);

This doesn't seem to work.

Answer

Greg Hewgill picture Greg Hewgill · May 9, 2009

Normally one uses the backslash character as the path separator in Windows. So:

ifstream file;
file.open("C:\\Demo.txt", ios::in);

Keep in mind that when written in C++ source code, you must use the double backslash because the backslash character itself means something special inside double quoted strings. So the above refers to the file C:\Demo.txt.