C++ Dosyaları


C++ Dosyaları

Kütüphane fstream, dosyalarla çalışmamıza izin verir.

fstreamKitaplığı kullanmak için hem standart <iostream> hem de <fstream>başlık dosyasını ekleyin:

Örnek

#include <iostream>
#include <fstream>

fstreamKitaplı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 ofstreamda fstreamsı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 ifstreamda 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 whilebirlikte 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();