bool functions
For the given input
1 2 3 4 5 6 7 8 9 10 11 12
|
std::ifstream fin; // 'f'ile in - fin
std::string filename = "fake.txt";
bool isOpen = GetInputFileStream(&fin, filename);
std::cout << filename << " open: ";
std::cout << std::boolalpha << isOpen << std::endl;
std::cout << std::endl;
filename = "real.txt";
isOpen = GetInputFileStream(&fin, filename);
std::cout << filename << " open: ";
std::cout << std::boolalpha << isOpen << std::endl;
std::cout << std::endl;
fin.close();
|
The output should be
1 2 3 4
|
Opening file fake.txt
fake.txt open: false
Opening file real.txt
real.txt open: true
|
But my bool function returns both as true this is what I have.
1 2 3 4 5 6 7 8 9
|
bool GetInputFileStream(std::ifstream * fin, std::string filename)
{
fin->open(filename);
std :: cout<< "opening file" << filename << std :: endl;
if(fin)
return true;
else
return false;
}
|
Last edited on
You are checking if the pointer is null or not.
If you want to check the state of the stream you have to dereference the pointer first.
The function should be checking whether the file exists or not
when I put (*fin) or (fin==nullptr) it now returns both as false
1 2 3 4 5 6 7 8 9 10 11 12 13
|
#include <iostream>
#include <string>
#include <fstream>
bool file_exists( std::string path ) // can_open_file_for_input( std::string path )
{ return std::ifstream(path).is_open() ; }
int main()
{
std::cout << std::boolalpha
<< file_exists( __FILE__ ) << '\n' // true
<< file_exists( "fake.txt" ) << '\n' ; // false
}
|
Topic archived. No new replies allowed.