用 C++ 寫入一個二進位制檔案


如果要使用 C++ 編寫一個二進位制檔案,請使用寫方法。用於寫入從“put”指標的位置開始的給定數量的位元組,流上。如果 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 << "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

更新於: 2019 年 7 月 30 日

7K+ 瀏覽

開啟您的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.