views:

3330

answers:

3

Hello,

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

Because it doesnt seem to work..I think..

Thanks in advance,

Greg

+2  A: 

You can use a full path with the fstream classes. The folowing code attempts to open the file demo.txt in the root of the C: drive. Note that as this is an input operation, the file must already exist.

#include <fstream>
#include <iostream>
using namespace std;

int main() {
   ifstream ifs( "c:/demo.txt" );       // note no mode needed
   if ( ! ifs.is_open() ) {                 
      cout <<" Failed to open" << endl;
   }
   else {
      cout <<"Opened OK" << endl;
   }
}

What does this code produce on your system?

anon
+1  A: 

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.

Greg Hewgill
All windows compilers that I'm aware of support the use of the forward slash in file names, and it should be used in preference to the backslash for portability.
anon
Win32 supports either "\" or "/" for paths, unless you are bypassing the path canonicalisation (paths starting with "\\?\"). See http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx
Richard
Neil, this has nothing to do with the compiler. The windows shell treats forward slashes the same way as back slashes. This has been the case since the early days of NT.
shoosh
The windows shell (if by that you mean cmd.exe) is in no way involved here.
anon
It doesn't even have anything to do with the shell, it's up to the kernel (Richard has it right). I said "normally" because you can still run into problems when using forward slashes because some programs interpret arguments starting with a forward slash as command line options instead of file names. You are correct that for just opening files, either forward or back slash should be fine. Convention prefers backslash.
Greg Hewgill
A: 

The code you presented is not enough to tell what the problem may be.
Why do you think that it does not work?
If it really does not work check if the file exists and that you have the access rights to the file.

lothar