I wrote a method which takes in a file name, checks if the file exists and has content, then proceeds to read 6 numbers in the file into 6 int
variables and return true
. If the file doesn't exist, or doesn't have content, it returns false.
However, when I call the method and give it a file that exists, it returns false. I'm not sure where I went wrong.
Here's my code:
bool readHSV(string the_file)
{
if(ifstream(the_file)){
fstream myfile(the_file, ios_base::in);
myfile >> h_min >> h_max >> s_min >> s_max >> v_min >> v_max;
cout << h_min << endl << h_max << endl << s_min << endl << s_max
<< endl << v_min << endl << v_max;
getchar();
return true;
}
return false;
}
The contents of the .txt file I am using:
4
22
68
192
162
247
You can use
<filesystem>
like this:The only way your function can return
false
is ififstream(the_file)
fails, meaning it can't open the file at all, whether it exists or not. If the file does exist butifstream
still fails, double check thatthe_file
contains the correct path and filename, and that your app has rights to access the file.Note that you are opening the file twice, once by
ifstream
and again byfstream
. You don't need to do that. You should open the file only once, and return true if you are able to read the values you want from it, eg: