Pliki C++


Pliki C++

Biblioteka fstreamumożliwia nam pracę z plikami.

Aby skorzystać z fstreambiblioteki, uwzględnij zarówno standardowy, jak <iostream> i plik <fstream>nagłówkowy:

Przykład

#include <iostream>
#include <fstream>

W fstreambibliotece znajdują się trzy klasy, które służą do tworzenia, zapisu lub odczytu plików:

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

Utwórz i zapisz do pliku

Aby utworzyć plik, użyj klasy ofstreamlub fstreami określ nazwę pliku.

Aby zapisać do pliku, użyj operatora wstawiania ( <<).

Przykład

#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();
}

Dlaczego zamykamy plik?

Jest to uważane za dobrą praktykę i może oczyścić niepotrzebne miejsce w pamięci.


Przeczytaj plik

Aby odczytać z pliku, użyj klasy ifstreamlub fstream i nazwy pliku.

Zauważ, że używamy również whilepętli razem z getline()funkcją (należącą do tej ifstreamklasy), aby odczytać plik wiersz po wierszu i wydrukować zawartość pliku:

Przykład

// 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();