File I/O
- A file is a collection of data stored on the disk
- We may wish to read from a file
- We may wish to create a file.
- This is very close to the I/O we have been doing.
- We need an additional header: #include <fstream>
- We need a new type
- ifstream inputfile;
- ofstream outputfile;
- We need to open the files
- inputfile.open("myfile"); // open for input
- outputfile.open("newfile"); // open for output
- CAUTION: opening an output file erases any existing file by
that name.
- We need to read from/ write to the files.
- inputfile >> avar; // read avar from the input file.
- outputfile << aver; // wwrite avar to the output file.
- We should close them when we are done.
- inputfile.close();
- outputfile.close();
- All of the rules for I/O that we have learned still apply,
(reading the wrong values and such)
- Open takes a C string not a C++ string.
Assume a person's information is stored in a datafile, write a program that
will read this information and print a formatted copy to the screen and
to a file. You should prompt for the input and output file names.
The file format is :
name name birth day occupation height weight
Example Input:
Smith John 10/10/80 Student 5'10 180
Sample Output:
John Smith,
Born: 10/10/80
Occupation: Student
Height: 5'10, Weight 180
Program Design
- Object Oriented Desgn: A technique for developing software in which the solution is expressed in terms of objects (self containted entities composed of data and operations on that data)
- Functional Decompisition: A technique for developing software in which the problem is divided into more easily handled subprograms, the soultions of which create a solution to the overall problem.
- OOP -start at the bottom and work your way up.
- FD - start at the top and work your way down.
- C++ is an Object Oriented Language.
- You have seen some of this
- ifstream infile;
- string filename;
- infile.open(filename.c_str());
- You will see MUCH more in 131
- Read pages 173 - 182
- Object Oriented Design
- Create objects that solve small problems.
- You can use existing classes, or create your own.
- You may even derive new classes from old ones.
- We need more C++ to be able to do this correctly.
- Functional Decompisition
- Try breaking the program into a series of steps.
- Each step is either simple, code it, or complex
- Break the complex steps down further.
- Structure chart.
-
- Zimmer's Program Guidelines
Two more programming problems for the day:
Both are from Essential C++ for Engineers and Scientists from Jeri R Hanly.