ifstream with wrong filename

Dec 18, 2018 at 7:23pm
Hi, another short question.

What happens if I call ifstream to process data from a file given by the string filename, but this file does not exist?
I assumed I would get an error, but it looks like my program will still run and only ignore the part where I am reading and processing data.

 
ifstream ist {filename};
Last edited on Dec 18, 2018 at 7:23pm
Dec 18, 2018 at 7:36pm
You can check if the file is open with if (!ist) //file is not open . Reading from or writing to an unopened std::fstream will fail silently, which is why it's important to always check the status of the stream.
Last edited on Dec 18, 2018 at 7:36pm
Dec 18, 2018 at 7:48pm
If you want an exception to be thrown as soon as an error occur you can enable this sort of behaviour using the exceptions function.

1
2
std::ifstream ist {filename};
ist.exceptions(std::ifstream::failbit);
Last edited on Dec 18, 2018 at 7:50pm
Dec 18, 2018 at 9:54pm
Thank you guys!
Topic archived. No new replies allowed.