Tệp C ++
Tệp C ++
Thư fstream
viện cho phép chúng tôi làm việc với các tệp.
Để sử dụng fstream
thư viện, hãy bao gồm cả tệp tiêu đề <iostream>
VÀ tiêu chuẩn <fstream>
:
Thí dụ
#include <iostream>
#include <fstream>
Có ba lớp được bao gồm trong fstream
thư viện, đượ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 tệp
Để tạo tệp, hãy sử dụng ofstream
hoặc fstream
lớp và chỉ định tên của tệp.
Để ghi vào tệp, hãy sử dụng toán tử chèn ( <<
).
Thí 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 tôi đóng tệp?
Nó được coi là thực hành tốt, và nó có thể dọn sạch không gian bộ nhớ không cần thiết.
Đọc tệp
Để đọc từ một tệp, hãy sử dụng ifstream
hoặc fstream
lớp và tên của tệp.
Lưu ý rằng chúng ta cũng sử dụng một while
vòng lặp cùng với getline()
hàm (thuộc về ifstream
lớp) để đọc từng dòng của tệp và in nội dung của tệp:
Thí 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();