File C++
File C++
fstream
Pustaka memungkinkan kita untuk bekerja dengan file .
Untuk menggunakan fstream
perpustakaan, sertakan standar <iostream>
DAN file <fstream>
header:
Contoh
#include <iostream>
#include <fstream>
Ada tiga kelas yang disertakan dalam fstream
perpustakaan, yang digunakan untuk membuat, menulis, atau membaca file:
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 |
Buat dan Tulis Ke File
Untuk membuat file, gunakan kelas ofstream
atau fstream
, dan tentukan nama file.
Untuk menulis ke file, gunakan operator penyisipan ( <<
).
Contoh
#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();
}
Mengapa kita menutup file?
Ini dianggap sebagai praktik yang baik, dan dapat membersihkan ruang memori yang tidak perlu.
Baca File
Untuk membaca dari file, gunakan kelas ifstream
or fstream
, dan nama file.
Perhatikan bahwa kami juga menggunakan while
loop bersama dengan getline()
fungsi (yang termasuk dalam ifstream
kelas) untuk membaca file baris demi baris, dan untuk mencetak konten file:
Contoh
// 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();