Opening any file

This code which is used as an example all over google works
 
   InFile.open("c:\test.dat",ios::in|ios::binary|ios::ate);

compiles and understood.

However I would like the file name to be generic...

The syntax for open is as I understand it is
 
   void open(const char *filename, ios::openmode mode);


So I tried

1
2
3
4
5
  string FileName; //is global variable defined elsewhere eg could be "c:test.txt"

  string *Name;//tried char as well just in case.
  Name=&FileName;
  InFile.open(*Name,ios::in|ios::binary|ios::ate);


gives me an error in open() probably because of the string pointer but is expecting a char pointer. I don't know why and I am not familiar with C++ errors.

In delphi I think you could do pchar(filename) from memory or something but is there a function to convert the FileName into a form that will be acceptable to use in open ()?

If someone could help me with this would appreciate it.

pzaw
Last edited on
I think the most common way is unfortunately

string filnam;
afile.open(filnam.c_str(), ...);

this is a miss in the language because file.open predates strings, there needs to be an overload for open(string, stuff) added.


string is NOT a char*.
string is a somewhat bloated class that contains a char*. And for the most part, you can avoid actually tapping the char* piece, but this is one place there isn't a better way.


Last edited on
this is a miss in the language because file.open predates strings, there needs to be an overload for open(string, stuff) added.

If you're using a C++11 or greater compatible compiler compiling for the C++11 or higher standard then you can just use a std::string.
1
2
3
   std::string file_name = "c:\test.dat";
   std::ifstream fin(file_name);


Note you should use of the class constructor whenever possible instead of the open() function.
Thanks everyone for your valuable contributions.

pzaw
Topic archived. No new replies allowed.