Đọc ghi file
Ta dùng #include <iostream> để đưa dữ liệu ra màn hình và #include <fstream> để đọc từ file.
Code minh họa
// ===== <fstream>: đọc/ghi file =====
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
{ ofstream f("data.txt"); // ghi đè file
f << "Dong 1\nDong 2\n";
} // ra khỏi khối: file tự đóng
{ ifstream f("data.txt");
string dong;
while (getline(f, dong)) cout << dong << "\n"; // đọc từng dòng
}
{ ofstream f("data.txt", ios::app); // ios::app: ghi nối vào cuối
f << "Dong 3 (noi them)\n";
}
ifstream g("khong_ton_tai.txt");
if (!g.is_open()) cout << "Khong mo duoc file!\n"; // luôn kiểm tra mở file
{ ifstream f("data.txt");
string tu; int dem = 0;
while (f >> tu) dem++; // đọc từng từ
cout << "So tu: " << dem << "\n"; }
return 0;
}
https://tritue.edu.vn/tuecode/tracnghiem30/site/data/YVdRc01qVTNMRjl5YjNWMFpTeGlZV2wyYVdWMEwzQnZjM1F2ZG1sbGR3PT0%3D