Tập tin C++
Tập tin C++
Thư viện fstream
cho phép chúng ta làm việc với các tập tin.
Để sử dụng thư viện fstream
, hãy bao gồm cả tệp tiêu đề <iostream>
VÀ <fstream>
tiêu chuẩn:
Ví dụ
#include <iostream>
#include <fstream>
Có ba lớp có trong thư viện fstream
, được sử dụng để tạo, ghi hoặc đọc tệp:
Class | Description |
---|---|
ofstream |
Creates and writes to files |
ifstream |
Reads from files |
fstream |
A combination of ofstream and ifstream: creates, reads, and writes to files |
Tạo và ghi vào một tập tin
Để tạo một tệp, hãy sử dụng lớp ofstream
hoặc fstream
và chỉ định tên của tệp.
Để ghi vào tệp, hãy sử dụng toán tử chèn ( <<
).
Ví dụ
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Create and open a text file
ofstream MyFile("filename.txt");
//
Write to the file
MyFile << "Files can be tricky, but it is fun
enough!";
//
Close the file
MyFile.close();
}
Tại sao chúng ta đóng tập tin?
Nó được coi là cách thực hành tốt và có thể dọn sạch không gian bộ nhớ không cần thiết.
Đọc một tập tin
Để đọc từ một tệp, hãy sử dụng lớp ifstream
hoặc fstream
và tên của tệp.
Lưu ý rằng chúng ta cũng sử dụng vòng lặp while
cùng với hàm getline()
(thuộc lớp ifstream
) để đọc từng dòng tệp và để in nội dung của tệp:
Ví dụ
// Create a
text string, which is used to output the text file
string myText;
// Read from the text file
ifstream MyReadFile("filename.txt");
// Use a while
loop together with the getline() function to read the file line by line
while (getline (MyReadFile,
myText)) {
// Output the text from the file
cout << myText;
}
// Close the file
MyReadFile.close();
Chạy ví dụ »