Open a file by its full path in C ++

I want the user to give me the full path where the file is located, not just the file name. How can I open the file this way?

It's something like this:

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

      

This does not work.

+14


a source to share


4 answers


Typically the backslash character is used as a path separator on Windows. So:

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

      



Keep in mind that when writing in C ++ source code, you must use a double backslash, because the backslash character means something special inside the double quotes. Thus, this refers to the file C:\Demo.txt

.

+15


a source


You can use the full path with the fstream classes. The following code tries to open the demo.txt file at the root of the C: drive. Note that since 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 do on your system?

+10


a source


The code seems to work for me. I think the same with @Iothar.

Check if you want to include the required headers for compilation. If it's compiled, check if there is such a file and that's it, names, etc. Matches and also check that you have permission to read the file.

To cross check if you can open it with fopen ..

FILE *f = fopen("C:/Demo.txt", "r");
if (f)
  printf("fopen success\n");

      

+2


a source


For those who get the path dynamically ... eg. drag & drop:

Some basic constructs get a drag & drop file with double quotes like:

"C:\MyPath\MyFile.txt"

      

A quick and pleasant solution is to use this function to remove characters from a string:

void removeCharsFromString( string &str, char* charsToRemove ) {
   for ( unsigned int i = 0; i < strlen(charsToRemove); ++i ) {
      str.erase( remove(str.begin(), str.end(), charsToRemove[i]), str.end() );
   }
} 

string myAbsolutepath; //fill with your absolute path
removeCharsFromString( myAbsolutepath, "\"" );

      

myAbsolutepath

now only contains C:\MyPath\MyFile.txt

The function needs these libraries: <iostream>

<algorithm>

<cstring>

.
This feature was based on this answer .

Working script: http://ideone.com/XOROjq

+1


a source







All Articles