การเขียน (Writing)
เขียน binary file ใน C++ ใช้ write method เขียนจำนวน bytes ที่กำหนดลง stream ตำแหน่ง put pointer ไฟล์จะขยายถ้า put pointer อยู่ท้ายไฟล์ หากอยู่กลางไฟล์ จะ overwrite
หากเกิด error ขณะเขียน stream จะอยู่ใน error state
Syntax of write method
ostream& write(const char*, int);
การอ่าน (Reading)
อ่าน binary file ใน C++ ใช้ read method ดึง bytes จำนวนที่กำหนดจาก stream วางใน memory ที่ parameter แรกชี้ ถ้า error stream จะ error state future read operations จะ fail
gcount() นับจำนวน characters ที่อ่านแล้ว clear() reset stream ให้ usable state
Syntax of read method
ifstream& write(const char*, int);
Algorithm
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