File Handling

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 26

File Input Output

In this week
• C++ input/output streams
• Input/output file streaming objects
• Working with input/output file streaming
objects
• Specifying the path of files
• End of file marker

1
C++ Input/Output Streams
• So far we have been working with console
input (keyboard) and output (screen) streams
• This was achieved with the #include <iostream>
directive
• In addition to console input output, C++
supports input/output file streams
• This is supported by #include <fstream>
directive

2
C++ Input/Output Streaming Objects
• C++ input/output streaming objects are special
objects in C++ that deliver inputs to our programs
and outputs from our programs
• cout is an output streaming object while cin is an
input streaming object
• These objects require the streaming in >> and
streaming out << operators in order to direct
input and output
• In order to work with input/output files, we need
C++ streaming objects that get connected to
physical files in the hard drive of a computer
3
C++ Input Output Streams
• The input/output file streamings are defined
in the std namespace inside the fstream
include directive
• Therefore we need to include the fstream
directive and also use the namespace std
• Once input/output file streaming object is
defined, it is used exactly as cout and cin
streaming objects together with the input >>
and output << streaming operators

4
File Output Stream
• In order to create an output file streaming object,
we construct an object of type ofstream
• ofstream stands for output file stream
• Syntax
ofstream fout;
• Once an output file streaming object is
constructed, we connect it to a file as follows
fout.open("ExampleOutputFile.txt");

5
File Output Stream
• Construction of output file streaming object and connecting it
to a file may also be done together in one C++ statement as
ofstream fout("ExampleOutputFile.txt");
• When we connect output file streaming object to a file in the
hard drive, then a new empty file will be created
automatically
• If the same file name already exists, then it will be
overwritten (i.e. the existing file will be deleted and a new
empty file with the same file name will be created)
• Moreover, in Visual C++ 2010 Express Edition, the file will be
created in the folder where the cpp file is located

6
File Output Stream
• Once the output file streaming object is constructed and connected
to a file on the hard drive, then it will be used together with the
output stream operator << in exactly the same way as cout object
• For cout, the output goes to the screen; while for fout the output
goes to the file
• Once we have finished using an output file streaming object, we
need to close it (disconnect it from the physical file in the hard
drive)
• In order to close an output file stream object, we do
fout.close();
• Once an output file streaming object is closed, it can no more be
used to write output to a file because it is disconnected from the
file; unless it is opened again and connected to a file.
7
File Output Stream
• The following program demonstrates, the construction, usage and closing
of output file streaming object. The created text file is also shown.

8
File Output Stream
• Like we said earlier, when we open an output file
streaming object; then by default the file is
created from scratch (that is if the same file name
exists, it will be overwritten)
• Sometimes, we may need to open an existing file
but we don’t want to overwrite it; instead we
would like to append data to it
• This is done by informing C++ our intention to
append when we open the file as shown below
9
File Output Stream
• In order to append new information to an existing file, we do
ofstream fout("ExampleOutputFile.txt", ios::app);
• Now what you write to fout will be appended to the contents of the file.
• The following program appends some data to an existing file. Assume the
file exists in the same folder where the cpp file is located. The existing file
is appended as expected as shown below.

10
File input stream
• We can also open an input stream object and
read data from a file to our program
• Syntax
ifstream fin;
fin.open("ExampleInputFile.txt");
• OR combining these two statements
in one
ifstream
fin("ExampleInputFile.txt");
• Then we can use fin together with the input
streaming operator >> just like we do with cin 11
File input stream
• For example, suppose there is a file named
ExampleInputFile.txt in the same folder where
our cpp file is located
• Moreover suppose the file contains five integer
numbers separated either by spaces, tabs or each
number on its own line
• Then the following program will read the five
numbers one by one using a loop and compute
the minimum number and display it onto the
screen
12
File input stream

13
File input stream
• Extra care needs to be followed when working
with file input stream objects
– Firstly we should be certain the physical file from
which to read exists
– Secondly, we should know the type of the data in
the file in order to read to proper data type
variables
– Thirdly, we should ascertain there is enough data
in the file to read

14
Specifying Path of Files
• Sometimes we may need to give an explicit
path to a file for input or output streaming
objects
• This is done by giving the full path when we
construct or open the file streaming object
• Example
ofstream fout("C:/Users/Me/Desktop/ExampleOutputFile.txt");

• This creates the file on the desktop


15
Checking IO stream
• It is important we check if an input/output file stream
object is opened correctly before using it
• Sometimes, output stream object may fail because we
don’t have the privilege to create a new file on the
computer we are using
• An input file stream may fail because there is no file with
the given file name in the folder we are specifying
• In order to check the success of input/output file stream
objects we proceed as follows:
ofstream fout("Test.txt") ifstream fin("Test.txt")
if (fout.fail()) if (fin.fail())
//File opening //File opening
failed failed
else else
//File opening //File opening
succeded succeded
16
Checking IO stream
• In the following example, we give a complete
example to create a new file, write data on it and
then read the data from the file and print it to the
screen
• We also demonstrate the full path of
input/output files specification in order to read
from or write to any folder of our choice
• We also check the success of our file input output
stream objects before we make use of the
objects
17
File IO Example

18
File IO Example

19
More General Complete Example
• Create a text file named ClassList.txt manually using notepad and edit it as follows
and save it somewhere on the computer

John Walter 20 19 45
Sara Gill 16 15 35
Mark Black 23 24 50
Jess Paul 10 20 25
Joe Nash 14 18 44

Think of these as students' full names and their assessment marks for exercises,
projects and final exam. Write a C++ program that reads this file (ClassList.txt) and
that creates a new file named Report.txt on the same folder with the same
content as the input file together with the letter grades of the students on the
same line for each student. For the letter grades, use the settings [90, 100] = A,
[75, 90) = B, [65, 75) = C, [50, 65) = D and [0, 50) = F.

20
More General Complete Example

21
More General Complete Example

22
End of File Marker
• Sometimes we may wish to read input data
from an input file but we may not know the
amount of data that is stored in the file
• In such cases, we need to loop reading until all
the data in the file is read
• That is, until we reach the END OF THE FILE
• C++ input streaming objects can test end of
file using eof() member function that returns
true when the end of file is reached

23
End of File Marker
• In order to demonstrate the eof member
function, assume there is an input text file named
TestInputFile.txt on the desktop of the computer
that we are working on
• Assume that this input text file contains some
integer numbers (but also assume that we don't
know how many numbers are in the file)
• Then the following program will read all the
numbers in the file and print the minimum and
maximum numbers in the file
24
End of File Marker
Input File Example

Output of the program

25
End of File Marker
• When using eof() member function of the input file streaming objects, it is
important not to have any extra empty lines at the end of the input file we
are reading from; for otherwise empty lines will be read before we can
reach the end of file marker
• Practice Question:- Given an input file that contains several integers, write
a C++ program that reads the numbers from the file and prints them to
the screen in reverse order (that is the first number read is printed last
and last number read is printed first)
One way is to use recursion which will require no arrays Of
course you can not use a static or dynamic array because it is not
known how many numbers the file contains; unless you scan the file
twice: once to count how many numbers there are in the file and then to
read the numbers in to a dynamic array

26

You might also like