Having trouble validating file names

Far from done but right now I am trying to get this program to ask for file name and store it in string then convert to ifstream and then check if file is valid by calling separate function isValid to check and it will return true if valid and false if not and if it is not valid is will ask again for an input but if it is valid it will call another function to open the file...


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

void Open_file(ifstream& my_file, string name)
{
my_file.open(name);
}


bool isValid(ifstream& file)
{
if (file.good())
{

return true;
}
else
{
return false;
}
}

string File_title(ifstream& my_file)
{
}


void Output_function(ifstream& my_file)
{
ofstream out_title("titles.txt", fstream::app);
out_title << File_title(my_file) << endl;


}



int main()
{
string file_name;
cout <<"please enter a HTML file name or hit 'exit' to quit and if you want to clear file please enter 'clear': ";
cin >> file_name;
ifstream my_file(file_name.c_str());



while (file_name != "exit")
{
while ((isValid(my_file)) == false)
{
cout <<"Invalid file name, please enter a valid file name: ";
cin >> file_name;
ifstream my_file(file_name.c_str());
}

Open_file(my_file, file_name);

}
}

closed account (48T7M4Gy)
Please use code tags <> around your code. See Format: on the right

Proper indentation would be a good idea too. :)
Last edited on
Actually you can't convert a string into an ifstream. You can create an ifstream object with a string as filename and check if the ifstream object is valid.

1
2
3
4
5
6
7
8
9
10
11
string filename;
getline(cin, filename); // might contain spaces so we can't use cin >> filename
ifstream src(filename.c_str());
if (src) // stream is valid
{
   // use src;
}
else
{
  // handle invalid filename
}
Topic archived. No new replies allowed.