用C ++编写二进制文件
要使用C ++编写二进制文件,请使用write方法。从“放置”指针的位置开始,它用于在给定的流上写入给定数量的字节。如果put指针在文件末尾是最新的,则扩展文件。如果此指针指向文件的中间,则文件中的字符将被新数据覆盖。
如果在写入文件的过程中发生任何错误,则将流置于错误状态。
写方法的语法
ostream& write(const char*, int);
算法
BeginCreate 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
以上是 用C ++编写二进制文件 的全部内容, 来源链接: utcz.com/z/316219.html