Soubory C++
Soubory C++
Knihovna fstream
nám umožňuje pracovat se soubory.
Chcete-li použít fstream
knihovnu, zahrňte standardní soubor <iostream>
A hlavičkový <fstream>
soubor:
Příklad
#include <iostream>
#include <fstream>
Knihovna obsahuje tři třídy fstream
, které se používají k vytváření, zápisu nebo čtení souborů:
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 |
Vytvořit a zapsat do souboru
Chcete-li vytvořit soubor, použijte třídu ofstream
nebo fstream
a zadejte název souboru.
Pro zápis do souboru použijte operátor vložení ( <<
).
Příklad
#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();
}
Proč soubor zavíráme?
Je to považováno za osvědčený postup a může to vyčistit zbytečný paměťový prostor.
Přečtěte si soubor
Chcete-li číst ze souboru, použijte třídu ifstream
nebo fstream
a název souboru.
Všimněte si, že také používáme while
smyčku spolu s getline()
funkcí (která patří do ifstream
třídy) pro čtení souboru řádek po řádku a pro tisk obsahu souboru:
Příklad
// 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();