File I/O in C++
File I/O in C++
File I/O in C++
stream - a sequence of characters interactive (iostream! cin + input stream associated *it$ keyboard. cout + output stream associated *it$ display. file (fstream! ifstream + defines ne* input stream (normally associated *it$ a file!. ofstream + defines ne* output stream (normally associated *it$ a file!.
.ote/ 0$ere is no 1.$2 on standard $eader files / 3fstream4 iostream ++ contains #asic information re5uired for all stream I/O operations iomanip ++ contains information useful for performing formatted I/O *it$ parameteri6ed stream manipulators fstream ++ contains information for performing file I/O operations strstream ++ contains information for performing in+memory I/O operations (i.e., into or from strings in memory!
ios is the base class. istream and ostream inherit from ios ifstream inherits from istream (and ios) ofstream inherits from ostream (and ios) iostream inherits from istream and ostream (& ios) fstream inherits from ifstream, iostream, and ofstream
C++ streams
#include <fstream> int main (void) { //Local declarations ifstream fs n! ofstream fs"ut! . . . return #! $
input_stream.open("numbers.dat" )
Calling Object Dot Operator File Name
ifstream fsin) fs3n.open"const char45 fname$ connects stream fs3n to t$e e9ternal file fname. fs3n.get"char6 character$ e9tracts ne9t c$aracter from t$e input stream fs3n and places it in t$e c$aracter varia#le character. fs3n.eof"$ tests for t$e end+of+file condition.
ofstream fsOut) fsOut.open"const char45 fname$ connects stream fsOut to t$e e9ternal file fname. fsOut.put"char character$ inserts c$aracter character to t$e output stream fsOut. fsOut.eof"$ tests for t$e end+of+file condition.
%unctions for binar0 file handlin4 4et()) read a b0te and 1oint to the ne(t b0te to read 1ut()) ,rite a b0te and 1oint to the ne(t location for ,rite read()) bloc5 readin4 ,rite()) bloc5 ,ritin4
6ome useful functions see54())Go to a specific position when reading see51())Go to a specific position when writing tell4()) Retunrs an int type, that shows the current position of
the inside-pointer. This one works only when you read a file.
tell1()) The same as tellg() but used when we write in a file. flush())Sa e data from the buffer to the output file.