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