用C ++编写二进制文件
要使用C++编写二进制文件,请使用write方法。从“放置”指针的位置开始,它用于在给定的流上写入给定数量的字节。如果put指针在文件末尾是最新的,则扩展文件。如果此指针指向文件的中间,则文件中的字符将被新数据覆盖。
如果在写入文件的过程中发生任何错误,则将流置于错误状态。
写方法的语法
ostream& 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 opens successfully, write the binary data using write method.
Close the file for writing.
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 << "不能打开文件!" << 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 << "写入时发生错误!" << 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
热门推荐
6 保研的祝福语简短
10 年轻20岁祝福语简短
11 朋友结婚祝福语信息简短
12 女孩婚礼贺卡祝福语简短
13 30段点歌简短祝福语
14 虎年春节祝福语图文简短
15 写给后妈祝福语大全简短
16 简短回复生日祝福语
17 校长送毕业祝福语简短
18 毕业立体贺卡祝福语简短