Home > Backend Development > C++ > How to read and write binary files using C++?

How to read and write binary files using C++?

WBOY
Release: 2024-06-01 21:21:00
Original
725 people have browsed it

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 using C++?

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();
Copy after login

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();
Copy after login

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;
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template