C++- bestanden
C++-bestanden
De fstream
bibliotheek stelt ons in staat om met bestanden te werken.
Om de fstream
bibliotheek te gebruiken, neemt u zowel het standaard- als het <iostream>
headerbestand<fstream>
op:
Voorbeeld
#include <iostream>
#include <fstream>
Er zijn drie klassen opgenomen in de fstream
bibliotheek, die worden gebruikt om bestanden te maken, te schrijven of te lezen:
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 |
Een bestand maken en naar een bestand schrijven
Om een bestand te maken, gebruikt u de klasse ofstream
of fstream
en geeft u de naam van het bestand op.
Gebruik de invoegoperator ( <<
) om naar het bestand te schrijven.
Voorbeeld
#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();
}
Waarom sluiten we het bestand?
Het wordt als een goede gewoonte beschouwd en het kan onnodige geheugenruimte opruimen.
Een bestand lezen
Om uit een bestand te lezen, gebruikt u de klasse ifstream
of fstream
en de naam van het bestand.
Merk op dat we samen met de functie (die bij de klasse hoort) ook een while
lus gebruiken om het bestand regel voor regel te lezen, en om de inhoud van het bestand af te drukken:getline()
ifstream
Voorbeeld
// 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();