To add a warning when the file cannot be opened, you should check if the file was successfully opened after creating the std::ifstream object. Here's the modified code with the warning:
std::string perimeterFileName = initFolder + "perimeters" + fileName + ".bin";
std::filesystem::path perimeterFilePath = perimeterFileName;
if (std::filesystem::exists(perimeterFilePath)) {
std::ifstream perimetersFile(
perimeterFileName,
std::ios::binary
);
// Check if the file was successfully opened
if (!perimetersFile.is_open()) {
std::cerr << "Warning: Could not open file " << perimeterFileName << std::endl;
} else {
perimetersFile.read(reinterpret_cast<char*>(perimeters), sizeof(unsigned int)* (amountOfCells+1));
perimetersFile.close();
}
}
Explanation:
is_open() check: After creating the ifstream object, we check if the file was successfully opened using is_open(). If not, a warning is printed to std::cerr (the standard error stream, which is appropriate for warnings/errors).
std::cerr: This is used instead of std::cout for error/warning messages, as it is unbuffered and more suitable for such output.
- Error handling: The actual file reading (
read) and closing (close) only happen if the file was successfully opened.
Alternative (More Concise):
You can also combine the existence check and the opening into a single step (though this changes the logic slightly, as it doesn't separately check for existence):
std::string perimeterFileName = initFolder + "perimeters" + fileName + ".bin";
std::ifstream perimetersFile(perimeterFileName, std::ios::binary);
if (!perimetersFile.is_open()) {
std::cerr << "Warning: Could not open file " << perimeterFileName << std::endl;
} else {
perimetersFile.read(reinterpret_cast<char*>(perimeters), sizeof(unsigned int)* (amountOfCells+1));
perimetersFile.close();
}
This version is simpler but doesn't explicitly check for file existence before attempting to open it. Choose the approach that fits your needs.