C/C++ 中的二进制文件读写
写入
要在 C++ 中写入二进制文件,请使用 write() 方法。它用于从给定位置开始,在给定流上写入指定数量的字节。“put”指针指示写入位置。如果“put”指针当前位于文件末尾,则文件将被扩展。如果该指针指向文件中间,则文件中的字符将被新数据覆盖。
如果在写入文件期间发生任何错误,则流将进入错误状态。
write() 方法的语法
ostream& write(const char*, int);
读取
要在 C++ 中读取二进制文件,请使用 read() 方法。它从给定流中提取指定数量的字节,并将它们放置到第一个参数指向的内存中。如果在读取文件期间发生任何错误,则流将进入错误状态,所有后续读取操作都将失败。
gcount() 可用于计算已读取的字符数。然后可以使用 clear() 将流重置为可用状态。
read() 方法的语法
ifstream& write(const char*, int);
算法
Begin Create a structure Student to declare variables. Open binary file to write. Check if any error occurs in file opening. Initialize the variables with data. If file open successfully, write the binary data using write method. Close the file for writing. Open the binary file to read. Check if any error occurs in file opening. If file open successfully, read the binary data file using read method. Close the file for reading. Check if any error occurs. Print the data. End.
示例代码
#include<iostream> #include<fstream> using namespace std; struct Student { int roll_no; string name; }; int main() { ofstream wf("student.dat", ios::out | ios::binary); if (!wf) { cout << "Cannot open file!" << endl; return 1; } Student wstu[3]; wstu[0].roll_no = 1; wstu[0].name = "Ram"; wstu[1].roll_no = 2; wstu[1].name = "Shyam"; wstu[2].roll_no = 3; wstu[2].name = "Madhu"; for (int i = 0; i < 3; i++) wf.write((char * ) & wstu[i], sizeof(Student)); wf.close(); if (!wf.good()) { cout << "Error occurred at writing time!" << endl; return 1; } ifstream rf("student.dat", ios::out | ios::binary); if (!rf) { cout << "Cannot open file!" << endl; return 1; } Student rstu[3]; for (int i = 0; i < 3; i++) rf.read((char * ) & rstu[i], sizeof(Student)); rf.close(); if (!rf.good()) { cout << "Error occurred at reading time!" << endl; return 1; } cout << "Student's Details:" << endl; for (int i = 0; i < 3; i++) { cout << "Roll No: " << wstu[i].roll_no << endl; cout << "Name: " << wstu[i].name << endl; cout << endl; } return 0; }
输出
Student’s Details: Roll No: 1 Name: Ram Roll No: 2 Name: Shyam Roll No: 3 Name: Madhu
另请阅读: C++ 文件和流
广告