Thư viện chuẩn iostream có cin để nhận đầu vào từ luồng chuẩn và cout để xuất ra luồng chuẩn. Bài viết hướng dẫn đọc dữ liệu từ file vào đối tượng lớp và ghi dữ liệu từ đối tượng lớp ra file.
Đọc/ghi file cần thư viện <fstream>. Ba kiểu dữ liệu chính:
- ifstream - luồng nhập file, đọc thông tin từ file.
- ofstream - luồng xuất file, ghi thông tin vào file.
- fstream - luồng file chung, có khả năng cả hai.
Tạo đối tượng lớp
Lấy lớp Employee với Name, Employee_ID, Salary là thành viên public.
class Employee {
public:
string Name;
long Employee_ID;
int Salary;
};
Employee Emp_1;
Emp_1.Name = "Jhonson";
Emp_1.Employee_ID = 212020;
Emp_1.Salary = 11000;
Tạo đối tượng file
Cú pháp
fstream/ofstream/ifstream ten_doi_tuong;
void open(const char *filename, ios::openmode);
ofstream file1;
file1.open("Employee.txt", ios::app);
- file1 mở file Employee.txt ở chế độ thêm (nội dung mới thêm vào cuối). Kiểu ofstream cho phép ghi vào file.
ifstream file2;
file2.open("Employee.txt", ios::in);
- file2 mở file Employee.txt ở chế độ đọc. Kiểu ifstream chỉ cho phép đọc.
Ghi và đọc đối tượng lớp
file1.write((char*)&Emp_1, sizeof(Emp_1));
- Ghi dữ liệu từ đối tượng Emp_1 vào file Employee.txt bằng write. (char*)&Emp_1 trỏ đến đầu đối tượng, sizeof(Emp_1) tính số byte ghi.
file2.read((char*)&Emp_1, sizeof(Emp_1));
- Đọc dữ liệu từ file vào đối tượng Emp_1 bằng read. (char*)&Emp_1 trỏ đến đầu đối tượng, sizeof(Emp_1) tính số byte đọc.
Đóng file
file1.close(); file2.close();
Đóng luồng nhập và xuất file.
Ví dụ
#include <iostream>
#include <fstream>
using namespace std;
class Employee {
public:
string Name;
int Employee_ID;
int Salary;
};
int main() {
Employee Emp_1;
Emp_1.Name = "John";
Emp_1.Employee_ID = 2121;
Emp_1.Salary = 11000;
// Ghi dữ liệu vào Employee.txt
ofstream file1;
file1.open("Employee.txt", ios::app);
file1.write((char*)&Emp_1, sizeof(Emp_1));
file1.close();
// Đọc dữ liệu từ Employee.txt
ifstream file2;
file2.open("Employee.txt", ios::in);
file2.seekg(0);
file2.read((char*)&Emp_1, sizeof(Emp_1));
printf("\nName :%s", Emp_1.Name.c_str());
printf("\nEmployee ID :%d", Emp_1.Employee_ID);
printf("\nSalary :%d", Emp_1.Salary);
file2.close();
return 0;
}
Đầu ra
Name: John Employee ID: 2121 Salary: 11000