C/C++ 中的二進位制檔案讀寫
寫入
要在 C++ 中寫入二進位制檔案,請使用 write() 方法。它用於從給定位置開始,在給定流上寫入指定數量的位元組。“put”指標指示寫入位置。如果“put”指標當前位於檔案末尾,則檔案將被擴充套件。如果該指標指向檔案中間,則檔案中的字元將被新資料覆蓋。
如果在寫入檔案期間發生任何錯誤,則流將進入錯誤狀態。
write() 方法的語法
ostream& write(const char*, int);
讀取
要在 C++ 中讀取二進位制檔案,請使用 read() 方法。它從給定流中提取指定數量的位元組,並將它們放置到第一個引數指向的記憶體中。如果在讀取檔案期間發生任何錯誤,則流將進入錯誤狀態,所有後續讀取操作都將失敗。
gcount() 可用於計算已讀取的字元數。然後可以使用 clear() 將流重置為可用狀態。
read() 方法的語法
ifstream& 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 open successfully, write the binary data using write method. Close the file for writing. Open the binary file to read. Check if any error occurs in file opening. If file open successfully, read the binary data file using read method. Close the file for reading. 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;
}
ifstream rf("student.dat", ios::out | ios::binary);
if (!rf) {
cout << "Cannot open file!" << endl;
return 1;
}
Student rstu[3];
for (int i = 0; i < 3; i++)
rf.read((char * ) & rstu[i], sizeof(Student));
rf.close();
if (!rf.good()) {
cout << "Error occurred at reading 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
另請閱讀: C++ 檔案和流
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP