Trong C++, để đọc và ghi file, bạn cần sử dụng lớp fstream
(file stream). Lớp này cung cấp các hàm để mở, đọc, ghi và đóng một file. Có 3 lớp con của fstream
là ifstream
(input file stream), ofstream
(output file stream) và fstream
(file stream).
Các bài viết liên quan
- Đọc file:
#include <fstream> #include <iostream> int main() { std::string line; std::ifstream file("example.txt"); if (file.is_open()) { while (getline(file, line)) { std::cout << line << std::endl; } file.close(); } else { std::cout << "Unable to open file"; } return 0; }
- Ghi file:
#include <fstream> #include <iostream> int main() { std::ofstream file("example.txt"); if (file.is_open()) { file << "Hello, World!" << std::endl; file << "This is a sample text." << std::endl; file.close(); } else { std::cout << "Unable to open file"; } return 0; }
- Thêm nội dung vào file:
#include <fstream> #include <iostream> int main() { std::ofstream file("example.txt", std::ios::app); if (file.is_open()) { file << "This text will be added to the end of the file." << std::endl; file.close(); } else { std::cout << "Unable to open file"; } return 0; }
Trong các ví dụ trên, ifstream
được sử dụng để đọc file, ofstream
được sử dụng để ghi file, và ios::app
được sử dụng để thêm nội dung vào file. Trước khi ghi hoặc đọc file, bạn cần mở file bằng cách sử dụng hàm open()
trong lớp `fstream`.
Các thao tác đọc và ghi file có thể thực hiện với các hàm khác nhau như read()
, write()
, get()
, put()
cũng như các hàm xử lý đặc biệt như seekg()
, seekp()
để di chuyển con trỏ vị trí đọc/ghi trong file.
Lưu ý rằng để ghi vào file, file phải có quyền ghi, để đọc file phải có quyền đọc. Nếu không có quyền, nó sẽ không thể mở file và sẽ xuất ra thông báo lỗi.
Cũng chú ý rằng, khi đọc và ghi file, nếu file không tồn tại sẽ tạo mới file với tên đã chỉ định, nếu file đã tồn tại thì nội dung của file sẽ bị thay đổi.