Programming and Problem Solving with C++, 2/e
Download
Report
Transcript Programming and Problem Solving with C++, 2/e
Lecture 31
Handling Selected Topics
Again!!
File I/O
Special Lectures
1
Motivation
As we have seen in the HW#3, the customer
information can expand to hundreds of data
items
Every time we start the program , it will be
impractical to type in all the amounts by hand
If computer shuts down due to power failure or
if system crashes, we lose all the information
Therefore the only practical way to handle large
amounts of data is to store the data on the hard
disk
2
We can do this using files
File Handling in C++
In C++, a file is taken as simply a sequence of
bytes
It is upto the programmer to decide the way to
store the data
For example, in HW3, the input file contained
customer number followed by amount of
purchase
It could be the other way round as well
3
File Access Methods
The file handling done by us is known as
“sequential access”
It is because we read and write from first item to
last item in linear order
In C++, it is also possible to use files in a
random access way
In random access, we can jump around, skip
blocks and move back and forth in the file
Random access needs istream and ostream
member functions get put read and write
4
Streams
A stream is a sequence of characters used for
program input or output
We normally include iostream library in our
programs
Including iostream enables us to use “cin”, the
standard input stream object and “cout”, the
standard output stream object
Including fstream enables us to handle files in
our programs, using ifstream objects for reading
and ofstream objects for writing to files
5
Copying One File to Another
We can write a simple utility just like the “copy”
command
The purpose is to copy one file to another
The program should be structured as follows:
6
Copying One File to Another
The #include and using commands
Declaring our own objects of type ifstream and
ofstream
Opening one file for reading
Opening another file for writing
Entering a loop while (!my_infile.eof()
Reading a character using my_infile.get(nextch)
Writing the just read character into the output
file using my_outfile.put(nextch)
7
Practice Exercise
Write a program to open and read a text
file character by character. Count the
occurrence of all vowels in the file.
When the end of file is reached, display
the vowels found in the file
8