Methods to read and write binary files in C++: Write binary files: Use the std::ofstream class and set the output mode to std::ios::binary. Read binary files: Use the std::ifstream class and set the input mode to std::ios::binary.
How to read and write binary files in C++
A binary file is a special file type that stores non-text data, e.g. Images, Audio and Archives. There are two main operations when working with binary files in C++: reading and writing.
Writing to binary files
Use the std::ofstream
class to write to binary files. When opening the file, specify the output mode as binary mode (std::ios::binary
).
// 打开文件以进行二进制写入 std::ofstream outFile("binaryFile.bin", std::ios::binary); // 向文件写入二进制数据 outFile.write((char*) &data, sizeof(data)); // 关闭文件 outFile.close();
Reading binary files
Use the std::ifstream
class to read binary files. Likewise, specify binary mode when opening the file.
// 打开文件以进行二进制读取 std::ifstream inFile("binaryFile.bin", std::ios::binary); // 从文件读取二进制数据 inFile.read((char*) &data, sizeof(data)); // 关闭文件 inFile.close();
Practical case: reading and displaying images
The following code snippet demonstrates how to read an image file in C++ and display it in the console:
#include <iostream> #include <fstream> #include <vector> int main() { // 二进制图像文件 std::string fileName = "image.bmp"; // 打开图像文件以进行二进制读取 std::ifstream inFile(fileName, std::ios::binary); // 检查文件是否打开 if (!inFile.is_open()) { std::cerr << "无法打开文件 " << fileName << std::endl; return 1; } // 获取文件大小 inFile.seekg(0, std::ios::end); size_t fileSize = inFile.tellg(); inFile.seekg(0, std::ios::beg); // 读取图像数据 std::vector<unsigned char> imageData(fileSize); inFile.read((char*) &imageData[0], fileSize); // 关闭文件 inFile.close(); // 在控制台中显示图像数据 for (unsigned char pixel : imageData) { std::cout << (int)pixel << " "; } return 0; }
This will print the value of each pixel in the image file.
The above is the detailed content of How to read and write binary files using C++?. For more information, please follow other related articles on the PHP Chinese website!