19. Advanced C++ Programming - Files and Streams
19. Advanced C++ Programming - Files and Streams
Programming
C++ Files and Streams
What is fstream library?
🞆 A file must be opened before you can read from it or write to it.
Either the ofstream or fstream object may be used to open a
file for writing and ifstream object is used to open a file for
reading purpose only.
fstream afile;
afile.open("file.txt", ios::out | ios::in );
OPENING A FILE: EXAMPLE
🞆 If you don’t specify the mode, each class has a default mode.
void close();
🞆 Following is an example for the standard syntax for close()
function:
ofstream outfile;
outfile.open("file.txt");
outfile.close();
WRITING TO A FILE:
OUTPUT FILE:
OTHER FUNCTIONS OF WRITING
CHARACTERS TO A FILE :
🞆 You read information from a file into your program using the
stream extraction operator (>>) just as you use that operator to
input information from the keyboard. The only difference is that
you use an ifstream or fstream object instead of the cin
object.
READING TO A FILE: EXAMPLE #1
char get();
🞆 Extract characters in a line
Functions Description
returns the current reading
int tellg();
position
returns the current writing
int tellp();
position
GET STREAM POSITIONING:
EXAMPLE
🞆 These functions allow to change the location of the get and put
positions. Both functions are overloaded with two different
prototypes. The first form is: <“\n” or newline is counted>