I'm trying to write a short program with a function ('OpenFil') that prompts the user for the name of a text file and then opens this using ifstream (passing it by reference). Then I call this function ('OpenFil') in the main in order to read in values from the text file in the main function. I know the file gets opened in the 'OpenFil' by it's not open in the main function. Can you please explain why this is so and help me to use the textfile in the main?
I can get it to work by simply including everything in the main function and not introducing the separate 'OpenFil' but I want to use this to builder a bigger program and so want to keep them separate. I also know the textfile I'm trying with is in the right directory. Thanks! My code is below:
int main(){
ifstream input;
OpenFil(input);
if(input.is_open())
cout<<"The file is open"<<endl;
else
cout<<"It's not open"<<endl;//this is what i get but don't want
system("PAUSE");
return 0;
}
void OpenFil(ifstream &input){//This is the function opening a textfile specified by the user
while(true){
cout<<"Enter a file name:"<<endl;
string FileName = GetLine();
ifstream input(FileName.c_str());//I have checked and the file IS open here definitely
if(input.is_open()) return;
cout<<"Sorry that name was not valid. Please try again."<<endl;
input.clear();
}
}
1) You create another instance of ifstream with the same identifier within OpenFil( ). 2) In OpenFil( ), you checked if the file was open (if( input.is_open( ) )). This is fine. However, is_open( ) returns a non-zero numerical value if the file was opened successfully. Your code, however, returns to the caller if the files opens. When the function reaches a return statement, the function ends. 3) In GetLine( ) you return to the caller before the cout statement is reached. 4) You've used system( ). 5) You've included <vector> which you don't use. 6) You've included <iomanip> which you don't use. 7) You've included <sstream> which you don't use.
Thanks! I didn't realize about not being able to use ifstream to open the function if I'd already passed the ifstream to the function. I changed the code to open the file to input.open and now it works!