ไลบรารีมาตรฐาน iostream มีสองเมธอดคือ cin สำหรับรับอินพุตจากสตรีมอินพุตมาตรฐาน และ cout สำหรับพิมพ์เอาต์พุตไปยังสตรีมเอาต์พุตมาตรฐาน ในบทความนี้เราจะเรียนรู้วิธีอ่านข้อมูลจากไฟล์เข้าไปในอ็อบเจกต์คลาส และวิธีเขียนข้อมูลในอ็อบเจกต์คลาสลงไฟล์
การอ่านและเขียนข้อมูลจาก/ไปไฟล์ต้องใช้ไลบรารีมาตรฐาน C++ อีกตัวคือ <fstream> สามชนิดข้อมูลหลักของ fstream ได้แก่:
- ifstream - แทน input file stream ใช้สำหรับอ่านข้อมูลจากไฟล์
- ofstream - แทน output file stream ใช้สำหรับเขียนข้อมูลลงไฟล์
- fstream - แทน general file stream มีความสามารถทั้งสองอย่าง
การสร้างอ็อบเจกต์คลาส
เราสร้างคลาส Employee ที่มี Name, Employee_ID, และ Salary เป็นสมาชิกข้อมูล public
class Employee {
public:
char Name[];
long Employee_ID;
int Salary;
};
Employee Emp_1;
Emp_1.Name = "Jhonson";
Emp_1.Employee_ID = 212020;
Emp_1.Salary = 11000;
การสร้างอ็อบเจกต์ไฟล์
Syntax
fstream/ofstream/ifstream object_name;
void open(const char *filename, ios::openmode);
ofstream file1;
file1.open("Employee.txt", ios::app);
- file1 เป็นอ็อบเจกต์ที่เปิดไฟล์ Employee.txt ในโหมด append (เนื้อหาใหม่จะถูกเพิ่มท้ายไฟล์) ชนิดของ file1 คือ ofstream หมายความว่าเราสามารถเขียนลง Employee.txt ได้
ifstream file2;
file2.open("Employee.txt", ios::in);
- file2 เป็นอ็อบเจกต์ที่เปิดไฟล์ Employee.txt ในโหมด input เพื่ออ่านเนื้อหา ชนิดของ file2 คือ ifstream หมายความว่าเราอ่านข้อมูลจาก Employee.txt ได้อย่างเดียว
การเขียนและอ่านอ็อบเจกต์คลาส
file1.write((char*)&Emp_1, sizeof(Emp1));
- ข้อมูลในอ็อบเจกต์คลาส Emp_1 ถูกเขียนลงไฟล์ Employee.txt โดยเรียกฟังก์ชัน write (char*)&Emp_1 ใช้ชี้ไปที่จุดเริ่มต้นของอ็อบเจกต์ และ sizeof(Emp_1) คำนวณจำนวนไบต์ที่คัดลอกลงไฟล์
file2.read((char*)&Emp_1, sizeof(Emp1));
- ข้อมูลในอ็อบเจกต์คลาส Emp_1 ถูกอ่านจากไฟล์ Employee.txt โดยเรียกฟังก์ชัน read (char*)&Emp_1 ใช้ชี้ไปที่จุดเริ่มต้นของอ็อบเจกต์ และ sizeof(Emp_1) คำนวณจำนวนไบต์ที่อ่านจากไฟล์
การปิดไฟล์
file1.close(); file2.close();
เพื่อปิด input stream และ output stream ของไฟล์
ตัวอย่าง
#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;
// เขียนข้อมูลนี้ลง Employee.txt
ofstream file1;
file1.open("Employee.txt", ios::app);
file1.write((char*)&Emp_1, sizeof(Emp_1));
file1.close();
// อ่านข้อมูลจาก 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;
}
ผลลัพธ์
Name: John Employee ID: 2121 Salary: 11000