เพื่อเขียนไฟล์ไบนารีใน C++ ใช้เมธอด write() ใช้เขียนจำนวนไบต์ที่กำหนดลงในสตรีม เริ่มจากตำแหน่งของ "put" pointer ไฟล์จะถูกขยายหาก put pointer อยู่ท้ายไฟล์ หากชี้กลางไฟล์ ข้อมูลเดิมจะถูกทับซ้อน
หากเกิดข้อผิดพลาดระหว่างเขียน สตรีมจะเข้าสู่สถานะข้อผิดพลาด
ไวยากรณ์ของเมธอด write
ostream& write(const char*, int);
อัลกอริทึม
Begin
Create structure Student with variables
Open binary file for writing
Check file open errors
Initialize variables with data
If file opens successfully, write binary data using write method
Close file
Check write errors
Print 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; }
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 << endl;
}
return 0;
}ผลลัพธ์
Student's Details: Roll No: 1 Name: Ram Roll No: 2 Name: Shyam Roll No: 3 Name: Madhu