Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

การเขียนไฟล์ไบนารีใน C++


ในการเขียนไฟล์ไบนารีใน C ++ ให้ใช้วิธีเขียน มันถูกใช้เพื่อเขียนจำนวนไบต์ที่กำหนดบนสตรีมที่กำหนด โดยเริ่มต้นที่ตำแหน่งของตัวชี้ "วาง" ไฟล์จะถูกขยายหากตัวชี้การวางปัจจุบันอยู่ที่ส่วนท้ายของไฟล์ หากตัวชี้นี้ชี้ไปที่ตรงกลางของไฟล์ อักขระในไฟล์จะถูกเขียนทับด้วยข้อมูลใหม่

หากมีข้อผิดพลาดเกิดขึ้นระหว่างการเขียนไฟล์ สตรีมจะอยู่ในสถานะข้อผิดพลาด

รูปแบบของวิธีการเขียน

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 << "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;
      cout << endl;
   }
   return 0;
}

ผลลัพธ์

Student’s Details:
Roll No: 1
Name: Ram
Roll No: 2
Name: Shyam
Roll No: 3
Name: Madhu