Dateizugriffe in C++
Beispiel
Ein Ausgabestrom kann wie ::std::cout verwendet werden.
Der Dozent wird hier auch ein paar Worte zu RAII sagen.
main.cpp
#include <string>
#include <iostream>
#include <fstream>
int main ()
{ ::std::ofstream file( "alpha" );
if( !file )::std::cerr << "Can’t open file.\n";
else file << "example\n"; }
Beispiel
Ein Eingabestrom kann wie ::std::cin verwendet werden.
main.cpp
#include <string>
#include <iostream>
#include <fstream>int main ()
{ ::std::ifstream file( "alpha" );
if( !file )::std::cerr << "Can’t open input file.\n";
else { char c; while( file.get( c ))::std::cout.put( c ); }}
Beispiel
Mit einem temporären Objekt in eine Textdatei schreiben. »app« steht für »append«.
main.cpp
#include <iostream>
#include <fstream>
#include <string>
int main()
{ ::std::ofstream( "tmp.txt" )<< ::std::string{ "alpha" }<< '\n';
::std::ofstream( "tmp.txt", ::std::ios::app )<< "beta" << '\n';
::std::cout << ::std::ifstream( "tmp.txt" ).rdbuf(); }main.cpp -- betriebssystemspezifische Version
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib> // ::std::systemint main()
{ ::std::ofstream( "tmp.txt" )<< ::std::string{ "alpha" }<< '\n';
::std::ofstream( "tmp.txt", ::std::ios::app )<< "beta" << '\n';
::std::system( "cd" );
::std::system( "dir tmp.txt" );
::std::system( "type tmp.txt" ); }
Datei kopieren mit Löschen aller »x«.
#include <iostream>
#include <istream>
#include <ostream>
#include <fstream>
#include <iterator>int main()
{ ::std::ifstream i{ "C:\\example\\source.txt" }; if( i )
{ ::std::ofstream o{ "C:\\example\\target.txt" }; if( o )
{ ::std::istreambuf_iterator< char >top;
::std::istreambuf_iterator< char >p{ i };
::std::ostreambuf_iterator< char >q{ o };
while( p != top )
{ char const ch = *p;
if( ch != 'x' )*q = ch;
++q; ++p; }}}}
Fehlerbehandlung (nach Di Bella )
#include <iostream>
#include <fstream>
#include <istream>
#include <ostream>int main()
{ if( auto in = ::std::ifstream{ "hello.txt" })
{ for( auto i = 0; in >> i; )
::std::cout << i << '\n';if( in.bad() )::std::cerr << "Non-recoverable device error.\n";
else if( in.fail() && !in.eof() )
::std::cerr << "Non-integral data read.\n"; }else
{ ::std::cerr << "Couldn't open hello.txt\n"; return 1; }}
UEBUNG F (nach der Datei-Lektion)
Schreiben Sie eine Funktion, die eine Referenz auf ein ::std::ostream-Objekt als Parameter hat und zwei Zufallszahlen (jeweils mit einem Zeilenende beendet) in den Strom schreibt. Rufen Sie diese Funktion dann mit den folgenden drei Argumenten auf:
- Einmal mit ::std::cout, um auf den Bildschirm zu schreiben
- Einmal mit einem ostream-Objekt, um in eine Textdatei zu schreiben
- Einmal mit einem stringstream-Objekt, um in einen Stringstream zu schreiben. (Zusatzanforderung D1: Geben Sie den Inhalt des Stringstreams dann auf den Bildschirm aus)