ifstream
und ofstream
.
Da diese beiden Kanal-Typen von den Standardstreams abgeleitet sind
existieren für sie alle Elementfunktionen der Standardstreams.
# include <fstream> double z=1.234; int m=5; ofstream outs ( "filename", ios::out ); // open the file with name // 'filename' for writing // ios::out can be skipped outs << x << '\n'; // the use of the self-defined output-stream outs << j << '\n'; // 'outs' is analogous to the use of 'cout' outs.close(); // close the out-fstream 'outs' ifstream ins ( "filename", ios::in ); // open the file with name // 'filename' to read from // ios::in can be skipped ins >> z; // the use of the self-defined input-stream ins >> m; // 'ins' is analogous to the use of 'cin' ins.close(); // close the in-fstream 'ins'Spätestens bei der Bearbeitung von Dateien benötigt man Informationen darüber, ob man am Ende des Files (EOF) angelangt ist, oder ob das Öffnen erfolgreich war. Dafür gibt es die sogenannten Statusinformationen, die je nach Zustand der Datei
true
oder false
zurückgeben:
ins.good() // true, if no error occured in stream 'ins' ins.eof() // true, if the end of file/stream is reached ins.bad() // true, if an hardware error occured ins.fail() // true, if a logical error or a // hardware error occured ins.clear() // set ins.good() to true ins.clear( ios::failbit | ins.rdstate() ) // set fail() manually to trueWie liest man nun aus einer Datei bis zu deren Ende? Die folgenden Beispiele sollen die Schwierigkeiten aufzeigen, auf die man bei der Implementierung dieser einfachen Aufgabe stoßen kann.
int n; while (!cin.eof()){ cin >> n; // .... this reads too far } while((cin >> n).good){ // ... this reads not far enough } while(cin >> n){ // ... this is the way it works }