在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