用 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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP