File Handling
Quick Notes
Section titled “Quick Notes”ifstream đọc file, ofstream ghi file, fstream đọc và ghi.
Luôn kiểm tra stream mở thành công.
Dùng RAII: file tự đóng khi stream ra khỏi scope.
Syntax
Section titled “Syntax”std::ifstream in("input.txt");std::ofstream out("output.txt");Example
Section titled “Example”#include <fstream>#include <iostream>#include <string>
int main(){ std::ifstream in("input.txt"); if (!in) { std::cerr << "cannot open input.txt\n"; return 1; }
std::string line; while (std::getline(in, line)) { std::cout << line << '\n'; }}| Mode | Meaning |
|---|---|
std::ios::in | Read |
std::ios::out | Write |
std::ios::app | Append |
std::ios::binary | Binary mode |
Common Mistakes
Section titled “Common Mistakes”- Không kiểm tra
if (!file)sau khi mở. - Nhầm path tương đối với working directory hiện tại.
- Ghi file text nhưng quên newline giữa các record.
Search Keywords
Section titled “Search Keywords”file handling xử lý file ifstream ofstream fstream read write append binary