#include#include int main() { std::ifstream in_file("example.txt"); if (in_file.fail()) { std::cerr << "Error opening file." << std::endl; return 1; } int num; while (in_file >> num) { std::cout << num << std::endl; } in_file.close(); return 0; }
#includeIn this example, we open a binary file named "binary.dat" for input in binary mode using an `ifstream` object. We then check if the file opening failed using the `fail()` method. If it did fail, we output an error message and exit the program. If it didn't fail, we read 4 bytes from the file using the `read()` method and store them in a character array. We then output the contents of the file by casting each character to an integer and printing it to the console. We then close the file using the `close()` method. The package library for `ifstream` is `fstream`.#include int main() { std::ifstream in_file("binary.dat", std::ios::binary); if (in_file.fail()) { std::cerr << "Error opening file." << std::endl; return 1; } char buffer[4]; in_file.read(buffer, 4); std::cout << "Contents of file: "; for (int i = 0; i < 4; i++) { std::cout << static_cast (buffer[i]) << " "; } std::cout << std::endl; in_file.close(); return 0; }