06 file processing

44
File Processing

Transcript of 06 file processing

Page 1: 06 file processing

File Processing

Page 2: 06 file processing

2

Hardware Model

Input Devices Memory (RAM) Output Devices

CPU

Storage DevicesTo this point we have been using the keyboard for input and the screen for output. Both of these are temporary.

Page 3: 06 file processing

3

Information Processing Cycle

InputRaw Data

Process (Application)

OutputInformation

StorageOutput from one process can serve as input to another process.

Storage is referred to as secondary storage, and it is permanent storage. Data is permanently stored in files.

Page 4: 06 file processing

4

Input and Output (I/O)• In the previous programs, we would enter the test data

and check the results. If it was incorrect, we would change the program, run it again, and re-enter the data.

• For the sample output, if we didn’t copy it when it was displayed, we had to run it again.

• Depending on the application, it may be more efficient to capture the raw data the first time it is entered and store in a file.

• A program or many different programs can then read the file and process the data in different ways.

• We should capture and validate the data at its points of origination (ie cash register, payroll clerk).

Page 5: 06 file processing

5

File I/O handled by Classes• Primitive data types include int, double, char, etc.• A class is a data type that has data (variables and values)

as well as functions associated with it.• The data and functions associated with a class are

referred to as members of the class.• Variables declared using a class as the data type are

called objects.• We’ll come back to these definitions as we go through an

example.• Sequential file processing – processing the records in

the order they are stored in the file.

Page 6: 06 file processing

6

Example Scenario

• We have a file named infile.txt

• The file has 2 records with hours and rate.

• We want to process the file by– reading the hours and rate – calculating gross pay– and then saving the results to outfile.txt

Page 7: 06 file processing

7

infile.txt40 10.0050 15.00

• This would be a simple text file.• The file can be created with Notepad or

some other text editor.• Just enter two values separated by

whitespace and press return at the end of each record.

Page 8: 06 file processing

8

fstream• We have been using #include <iostream> because this

is where cin and cout are defined.• We now need to #include <fstream> because this is

where the commands to do file processing are defined.• fstream stands for File Stream.• We can have input and output file streams, which

are handled by the classes ifstream and ofstream.• Recall that a stream is a flow characters.

– cin is an input stream.

– cout is output stream.

Page 9: 06 file processing

9

Sample Program#include <iostream> // cin and cout#include <fstream> // file processingusing namespace std;

void main ( ){

int hours;double rate, gross;ifstream inFile; //declares and assigns a ofstream outFile; //variable name to a stream

Page 10: 06 file processing

10

Open Function ifstream inFile;

//ifstream is the class (data type)//inFile is the object (variable)

inFile.open(“infile.txt”);

//open is a function associated with the object inFile//open has parenthesis like all functions ( )//The function call to open is preceded by the object name and dot operator.//We pass open( ) an argument (external file name).

Page 11: 06 file processing

11

Internal and External File Names ifstream inFile;

inFile.open(“infile.txt”);

• inFile is the internal file name (object).• infile.txt is the external file name.• open connects the internal name to the external file.• Naming conventions for the external file names vary by

Operating Systems (OS).• Internal names must be valid C++ variable names.• In the open is the only place we see the external name.

Page 12: 06 file processing

12

Check if Open was Successful

• after calling open ( ), we must check if it was successful by using fail().

if ( inFile.fail() ) //Boolean{

cout << “Error opening input file…”;exit (1); //<cstdlib>

}

Page 13: 06 file processing

13

Open outfile.txt

outFile.open(“outfile.txt”);

if ( outFile.fail() )

{

cout << “Error opening output file…”;

exit (1);

}

Page 14: 06 file processing

14

Quick Reviewvoid main ( ){

int hours; double rate, gross;ifstream inFile;ofstream outFile;

inFile.open(“infile.txt”);

if ( inFile.fail() ) {

cout << “Error …”;exit (1);

}

outFile.open(“outfile.txt”);

if ( outFile.fail() )

{

cout << “Error…”;

exit (1);

}

Page 15: 06 file processing

15

Recall infile.txt?40 10.00

50 15.00

• Recall that we are processing infile.txt.

• The next slide shows the while loop.

• The two values have been entered separated by whitespace and there is carriage return at the of each record (also whitespace).

Page 16: 06 file processing

16

Process the fileinFile >> hours >> rate; // read first record// cin >> hours >> rate; //same extractors

while (! inFile.eof() ){

gross = hours * rate;outFile << hours << rate << gross << endl; //write

// cout << hours << rate << gross << endl;

inFile >> hours >> rate; //read next record}

infile.txt

40 10.0050 15.00eof

Page 17: 06 file processing

17

outfile.txt

40 10.00 400.00

50 15.00 750.00

• Assumes decimal formatting was applied.

Page 18: 06 file processing

18

Close FilesinFile.close( );outFile.close( );

• Release files to Operating System (OS).

• Other users may get file locked error.

• Good housekeeping.

Page 19: 06 file processing

19

while vs do-while

inFile >> hours >> rate;

while (! inFile.eof() )

{

gross = hours * rate;

outFile << hours << rate << gross <<

endl;

inFile >> hours >> rate;

}

do{

inFile >> hours >> rate;gross = hours * rate;outFile << hours << rate

<< gross << endl;

} while (! inFile.eof() )//writes last record twice.

Outfile.txt

40 10.00 400.0050 15.00 750.0050 15.00 750.00

Page 20: 06 file processing

20

Empty infile.txt

inFile >> hours >> rate;

while (! inFile.eof() ){

gross = hours * rate;outFile << hours << rate

<< gross << endl; inFile >> hours >> rate;

}//while will leave outfile

empty.

do{

inFile >> hours >> rate;gross = hours * rate;outFile << hours << rate

<< gross << endl;

} while (! inFile.eof() )//do-while writes garbage

Outfile.txt

?? ??.?? ??.??

Page 21: 06 file processing

21

Do-while and File Processing• Do-while processes last record twice.

• Do-while does not handle empty files.

• Use a while loop for file processing.

Page 22: 06 file processing

22

Constructors and Classes

• Classes are defined for other programmers to use.• When an object is declared using a class, a special

function called a constructor is automatically called.

• Programmers use constructors to initialize variables that are members of the class.

• Constructors can also be overloaded to give programmers options when declaring objects.

Page 23: 06 file processing

23

ifstream Constructor Overloaded

• Default constructor takes no parameters.ifstream inFile;inFile.open(“infile.txt”);

• Overloaded constructor takes parameters.ifstream inFile (“infile.txt”);

Declare object and open file on same line.Gives programmer options.

Page 24: 06 file processing

24

Magic Formula• Magic formula for formatting numbers to two

digits after the decimal point works with all output streams (cout and ofstreams).

cout.setf(ios::fixed) outFile.setf(ios::fixed)cout.setf(ios::showpoint)

outFile.setf(ios::showpoint)cout.precision(2) outFile.precision(2)

• Note that cout and outfile are objects and setf and precision are member functions.

Page 25: 06 file processing

25

Set Flag• setf means Set Flag.

• A flag is a term used with variables that can have two possible values.– On or off, 0 or 1– Y or N, True or false

• showpoint or don’t showpoint.• Use unsetf to turn off a flag.

cout.unsetf(ios::showpoint)

Page 26: 06 file processing

26

Right Justification

• To right justify numbers, usethe flag named right and the function named width together.

• Numbers are right justified by default.• Strings are left justified by default.

cout.setf(ios::right);cout.width(6);

Page 27: 06 file processing

27

Using right and width( )outFile.setf(ios::right);

outFile.width(4); //use four spacesoutFile << hours ; //_ _40outFile.width(6);outFile << rate; //_ _40 _10.00

Have to enter four different commands; it’s a lot of typing…

Page 28: 06 file processing

28

Manipulator

• Short cut to call a formatting function.

outFile.setf(ios::right);

outFile << setw(4) << hours << setw(6) << rate;

//need #include <iomanip>

Page 29: 06 file processing

29

Formatted I/O• cin uses formatted input.• If you cin an integer or double, it knows how to get

those values.• If you enter an alpha character for a cin that is

expecting a number, the program will bomb (try it).• To control for this, you need to get one character at a

time and then concatenate all of the values that were entered.

• For example, for 10.00, you would get the 1, 0, a period, 0, and then another 0.

• If the values were all valid, you would convert these characters into a double using some built in predefined functions (atof, atoi).

Page 30: 06 file processing

30

Character I/O Functions

• We actually use some of character I/O functions in our displayContinue().

• To get one character including white space use get.cin.get(char);

• To get entire line up to the newline use getline.cin.getline(char, intSize);

• To put out one character use put.cout.put(char);

Page 31: 06 file processing

31

Functions to Check Value

• After you get one character, you will need to check what it is.

isalpha(char) - (a-z)

isdigit(char) - (0-9)

isspace(char) - (whitespace)

isupper(char) – (checks for uppercase)

islower(char) – (checks for lowercase)

Page 32: 06 file processing

32

Functions to Change Value• These functions can change the case if the

value in the char variable is an alpha.

tolower(char)toupper (char)

Is the following statement true or false?

if (islower(tolower(‘A’))) //true or false

Page 33: 06 file processing

33

ASC II Table• Review the ASCII table available on the website.• ASCII table shows the binary value of all characters.• The hexadecimal values are also presented because

when a program aborts and memory contents are displayed, the binary values are converted to hexadecimal (Hex).

• The Dec column shows the decimal value of the binary value.

• Look up CR, HT, Space, A, a• It shows that the values for a capital A is the same as

a lowercase a.• The values also inform us how data will be sorted.

Page 34: 06 file processing

34

Control Structures Reviewed

• 1st Sequence Control

• 2nd Selection Control (if, if-else)

• 3rd Repetition Control (while, do-while)

• 4th Case Control – Also known as Multiway Branching (if-else)– Related to Selection Control

• The switch statement is an alternative to if-else statements for handling cases.

Page 35: 06 file processing

35

Switch Example – main() void main(){

char choice; 

do // while (choice != 'D'){

cout << "Enter the letter of the desired menu option. \n" << "Press the Enter key after entering the letter. \n \n"

<< " A: Add Customer \n" << " B: Up Customer \n" << " C: Delete Customer \n" << " D: Exit Customer Module \n \n"

 

<< "Choice: ";  cin >> choice;

Page 36: 06 file processing

36

switch (choice) //controlling expression

{

case 'A':

addCustomer();

break;

case 'B':

upCustomer();

break;

case 'C':

deleteCustomer();

break;

case 'D':

cout << "Exiting Customer Module...please wait.\n\n";

break;

default:

cout << "Invalid Option Entered - Please try again. \n\n";

} // end of switch 

} while (choice != 'D');

} // end of main

case ‘a’:

Page 37: 06 file processing

37

Controlling Expression

• The valid types for the controlling expression are– bool

– int

– char

– enum

• Enum is list of constants of the type int– Enumeration

– Enum MONTH_LENGTH { JAN = 31, FEB = 28 …};

– Considered a data type that is programmer defined.

Page 38: 06 file processing

38

Switch Statement Summary• Use the keyword case and the colon to create a

label.– case ‘A’:– A Label is a place to branch to.

• Handle each possible case in the body.• Use the default: label to catch errors.• Don’t forget the break statement, or else the

flow will just fall through to next command.• Compares to an if-else statement.

Page 39: 06 file processing

39

Break Statement

• The break statement is used to end a sequence of statements in a switch statement.

• It can also be used to exit a loop (while, do-while, for-loop).

• When the break statement is executed in a loop, the loop statement ends immediately and execution continues with the statement following the loop.

Page 40: 06 file processing

40

Improper Use of Break

• If you have to use the break statement to get out of a loop, the loop was probably not designed correctly.

• There should be one way in and one way out of the loop.

• Avoid using the break statement.

Page 41: 06 file processing

41

Break Exampleint loopCnt = 1;while (true) //always true{

if (loopCnt <= empCnt) //Boolean is inside the loopbreak;

getRate()getHours() calcGross()displayDetails()loopCnt++;

}

Page 42: 06 file processing

42

Continue Statement

• The continue statement ends the current loop iteration.

• Transfers control to the Boolean expression.

• In a for loop, the statement transfers control to the up expression.

• Avoid using the continue statement.

Page 43: 06 file processing

43

Continue Exampleint loopCnt = 1;while (loopCnt <= empCnt){

getRate()getHours() calcGross()if (gross < 0 ) //skip zeros{

loopCnt++continue; //go to top of loop

}

displayDetails()loopCnt++;

}

Page 44: 06 file processing

44

Summary

• File Processing

• Introduced classes and objects

• Formatting flags and functions

• Character I/O and functions

• ASCII Table

• Switch Statement