C++ Dosyaları
C++ Dosyaları
Kütüphane fstream
, dosyalarla çalışmamıza izin verir.
fstream
Kitaplığı kullanmak için hem standart <iostream>
hem de <fstream>
başlık dosyasını ekleyin:
Örnek
#include <iostream>
#include <fstream>
fstream
Kitaplıkta dosya oluşturmak, yazmak veya okumak için kullanılan üç sınıf vardır :
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 |
Dosya Oluşturma ve Dosyaya Yazma
Bir dosya oluşturmak için ya ofstream
da fstream
sınıfı kullanın ve dosyanın adını belirtin.
Dosyaya yazmak için ekleme operatörünü ( <<
) kullanın.
Örnek
#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();
}
Dosyayı neden kapatıyoruz?
İyi bir uygulama olarak kabul edilir ve gereksiz bellek alanını temizleyebilir.
Dosya Oku
Bir dosyadan okumak için ya ifstream
da fstream
sınıfı ve dosyanın adını kullanın.
Dosyayı satır satır okumak ve dosyanın içeriğini yazdırmak için (sınıfa ait olan) işlevle while
birlikte bir döngü de kullandığımızı unutmayın :getline()
ifstream
Örnek
// 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();