Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình C

Đọc/ghi file nhị phân trong C/C++


Ghi file

Để ghi file nhị phân trong C++ dùng phương thức write. Nó ghi số byte cho trước trên luồng, bắt đầu từ vị trí con trỏ "put". File mở rộng nếu con trỏ put ở cuối file. Nếu con trỏ giữa file, ký tự bị ghi đè.

Nếu lỗi khi ghi, luồng chuyển trạng thái lỗi.

Cú pháp write

ostream& write(const char*, int);

Đọc file

Để đọc file nhị phân trong C++ dùng phương thức read. Nó trích số byte cho trước từ luồng vào bộ nhớ trỏ bởi tham số đầu. Nếu lỗi đọc, luồng chuyển trạng thái lỗi, mọi đọc sau thất bại.

gcount() đếm số ký tự đã đọc. clear() reset luồng về trạng thái dùng được.

Cú pháp read

istream& read(const char*, int);

Thuật toán

Bắt đầu
    Tạo cấu trúc Student khai báo biến
    Mở file nhị phân để ghi
    Kiểm tra lỗi mở file
    Khởi tạo biến với dữ liệu
    Nếu mở thành công, ghi dữ liệu nhị phân dùng write
    Đóng file ghi
    Mở file nhị phân để đọc
    Kiểm tra lỗi mở file
    Nếu mở thành công, đọc dữ liệu nhị phân dùng read
    Đóng file đọc
    Kiểm tra lỗi
    In dữ liệu
Kết thúc

Ví dụ mã

#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::in | 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;
}

Kết quả

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