### Chương trình C++ để đọc và ghi dữ liệu vào tệp
```cpp
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Ghi dữ liệu vào tệp
ofstream outFile("data.txt");
if (outFile.is_open()) {
outFile << "Hello, World!" << endl;
outFile << "This is a sample text file." << endl;
outFile.close();
cout << "Dữ liệu đã được ghi vào tệp data.txt." << endl;
} else {
cout << "Không thể mở tệp để ghi!" << endl;
}
// Đọc dữ liệu từ tệp
ifstream inFile("data.txt");
string line;
if (inFile.is_open()) {
cout << "Nội dung của tệp data.txt:" << endl;
while (getline(inFile, line)) {
cout << line << endl;
}
inFile.close();
} else {
cout << "Không thể mở tệp để đọc!" << endl;
}
return 0;
}
```
### Các phương thức mở tệp trong C++
1. **`ofstream`**: Mở tệp để ghi.
```cpp
ofstream outFile("filename.txt");
```
2. **`ifstream`**: Mở tệp để đọc.
```cpp
ifstream inFile("filename.txt");
```
3. **`fstream`**: Mở tệp cho cả việc đọc và ghi.
```cpp
fstream file("filename.txt", ios::in | ios::out);
```