File Streams
File Streams
Objective
Streams #include<fstream>
Creating Streams
ifstream ofstream
in_stream; out_stream;
respectively create a stream called "in_stream"
belonging to the class (like type) "ifstream" (input-
file-stream),
ofstream
• This data type represents the output file stream and is
used to create files and to write information to files.
ifstream
fstream • This data type represents the input file stream and is
used to read information from files.
fstream
• This data type represents the file stream generally, and
has the capabilities of both ofstream and ifstream
which means it can create files, write information to
files, and read information from files.
Having created a stream, we can connect it to a file
using the member function "open(...)”
Files • in_stream.open("Lecture_4");
To connect the ofstream "out_stream" to Although this connects "out_stream" to To disconnect connect the ifstream
the file "Lecture_4", we use an analogous "Lecture_4", it also deletes the previous "in_stream" to whatever file it is
statement: contents of the file, ready for new input. connected to, we write:
out_stream.open("Lecture_4"); in_stream.close();
Connecting THE STATEMENT: OUT_STREAM.CLOSE();
and
Disconnecting
Streams to
Files
HAS A SIMILAR EFFECT, BUT IN IN THIS CASE, THE FILE "LECTURE_4"
ADDITION THE SYSTEM WILL STILL EXISTS, BUT IS EMPTY.
"CLEAN UP" BY ADDING AN "END-
OF-FILE" MARKER AT THE END OF
THE FILE.
Example
This code creates a
file
called example.txt and
inserts a sentence
into it in the same
way we are used to
do with cout, but
using the file
stream myfile instead.
The first operation generally performed
on an object of one of these classes is to
associate it to a real file.
How to Open a
file An open file is represented within a
program by a stream (i.e., an object of
one of these classes; in the previous
This procedure is known as to open a
example, this was myfile) and any input
file.
or output operation performed on this
stream object will be applied to the
physical file associated to it.
In order to open a file with a stream object we use its
member function open:
myfile.close();
This member function takes flushes the associated buffers and closes the file:
Closing a file
myfile.close();
Once this member function is
In case that an object is destroyed
called, the stream object can be re-
while still associated with an open
used to open another file, and the
file, the destructor automatically
file is available again to be opened
calls the member function close.
by other processes.
Reading from a
file (Example)
• Reading from a file can also be
performed in the same way as was
done with cin: