Here is the code from cplusplus.com/reference
#include <iostream> // std::cerr
#include <fstream> // std::ifstream
int main () {
std::ifstream file;
file.exceptions ( std::ifstream::failbit | std::ifstream::badbit );
try {
file.open ("test.txt");
while (!file.eof()) file.get();
file.close();
}
catch (std::ifstream::failure e) {
std::cerr << "Exception opening/reading/closing file\n";
}
return 0;
}
My code is very similar
int main()
{
std::vector<int> numbers;
std::vector<std::ifstream *> ifs;
std::array<std::string, 3> files = {
"f1.txt", "f2.txt", "f3.txt"
};
for (int i = 0; i < files.size(); ++i) {
std::ifstream *_ifs = new std::ifstream;
ifs.push_back(_ifs);
ifs[i]->exceptions( std::ifstream::failbit | std::ifstream::badbit );
}
try {
int n;
std::string line;
for (int i = 0; i < files.size(); ++i) {
ifs[i]->open(files[i]);
while (!ifs[i]->eof()) {
std::getline(*ifs[i], line);
std::istringstream iss(line);
while (iss >> n) {
if (n % 3 == 0 && n % 5 == 0 && n % 7 == 0)
numbers.push_back(n);
}
}
ifs[i]->close();
}
} catch (std::ifstream::failure e) {
std::cerr << "Error reading from files: " << e.what() << std::endl;
return 1;
}
for (int i = 0; i < ifs.size(); ++i)
delete ifs[i];
ifs.clear();
std::cout << "Files have been read\n";
// Do something with numbers
// ...
}
The issue is that nothing is read. Exception is thrown almost immediatly. If I comment out failbit
from exceptions everything works fine, but exceptions are not thrown when the files are missing on Windows. On Ubuntu, without failbit
exceptions are thrown when the files are missing, and everything is read correctly. But with failbit
on Ubuntu as well exception is thrown at the beginning of reading and nothing is read. I tried to google it. Found the example from cplusplus.com . And stackoverflow question where the answer was not to check for eof, but instead read this way while(getline(ifs, line)) { /* do something with line */ }
. I tried this, and got no difference. Before I did these kinds of tasks throwing user defined classes. This time I decided to try standard library for that and it seems like I am missing something.