Reputation: 8991
Is there any reason why Dev C++
is not letting me do file.open(file_name_variable)
? I don't understand why it's not letting me open anything but a hardcoded name like file.open("abc.txt")
how do get around this? Don't use Dev C++?
here's basically what I have:
int open_file(string file_name){
ifstream file;
file.open(file_name);
if (!file.is_open()){
return 0;
}
return 1;
}
Upvotes: 0
Views: 4522
Reputation: 103703
You need to pass it a c-string. Use:
file.open( file_name.c_str() );
In C++11, this is no longer necessary. A signature that takes std::string
was added.
Upvotes: 6
Reputation: 10917
fstream::open
requires a const char *
as first argument.
void open ( const char * filename,
ios_base::openmode mode = ios_base::in | ios_base::out );
It does not take a std::string
(which is a shame by the way).
You need to convert your std::string
to a const char *
file.open(file_name.c_str())
Upvotes: 1
Reputation: 20616
Alexandre's right, I think. The signature of open is:
void open(const char *filename, ios_base::openmode mode);
You're trying to pass a std::string in as a const char *, but std::string doesn't have an operator const char * (for safety reasons). Instead, you have to use the c_str() method. The issue is not that the implicit conversion to const char * should be available, but that basic_ifstream should have an open overload that accepts a string -- to the best of my knowledge, this is being added in C++0x, but I don't have a reference for that offhand.
Upvotes: 0