57
“After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more work than people is that they never have to stop and answer the phone” Saturday March 07, 2009

“After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

Embed Size (px)

Citation preview

Page 1: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

“After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain”

“One good reason why computers can do more work than people is that they never have to stop and answer the phone”

Saturday March 07, 2009

Page 2: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

Introduction to Programming

Lecture 9

Page 3: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

What is a File?

• Combination of characters, words, sentences and paragraph are called as file.

• Two Types of files– Text File (readable English characters)– Executable program file (Dos Command)

Page 4: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

File Properties

• Name of the file• Path of the file (Absolute & Relative)• Length of the file• Date of Creation • File Access

Page 5: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

Why do we need files?

• Information of the computer is volatile• Execute the program and the data is saved on

the hard disk.• e.g Payroll system for SEECS Employees• Store information once and reuse it• Read/write/manipulate the data is File

handling

Page 6: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

File Handling

• Two ways to Access the Files– Sequential Access File– Random Access File

Page 7: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

Text File Handling

• Basic steps for File handling

– Open the file– Read and Write – Close the File

Page 8: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

Cont…

• Previously we worked with “cin” and “cout”.• Concept of Streams• During File Handling a header file called

“<fstream.h>” is to be included.• <fstream.h> is a header file for file streams.

Page 9: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

9

Read and Write file

• When we read the file, it means that file is used as an input for the program.

• We need to have a stream for input file• ifstream ( input file stream)

• In order to read and write from the same file , ofstream.

Page 10: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

Declaring File Stream (Step 1)

ifstream inFile; //object for reading from file

ofstream outFile; //object for writing into file

NOTE: The variable/ objects inFile and outFile are used as

“handle to refer” files.

Page 11: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

Cont…..(Step 2)

• So far we didn’t attach the file with a handle.– ifstream myFile;

• We must open a file. • For this we will use a function “Open”.

– myFile.open(Filename);Note: Absolute / Relative Path for Filename

Page 12: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

Cont…..(Step 3)

• Tell the compiler what you want to do with file i.e read, write or modify .

• Once the file is opened we can read it. myFile>>c;

/* The first word of the file will be read in c, where c is a character array, same as using cin. */

Page 13: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

Cont…

myFile>>c1>>c2>>c3;

// The first word will be read in c1,2nd in c2, 3rd in c3.

Page 14: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

Cont….(Step 4)

• File must be closed and it is the responsibility of programmer to close the file.

• myFile.close();• No argument in close function.

Page 15: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

Think…….

• What is the File that we are trying to open does not exist on the disk?????????

Page 16: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

Error Checking Mechanism

• It is very important• ifstream myFile; myFile.open(“mytext.txt”);

/*If this file does not exists on the disk, the variable myFile will not be associated with any file. We must make sure that the file opening process is successful. */

Page 17: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

Cont…

If(!myFile) { cout<<“There is some error opening the

file”<<endl; cout<<“ File cannot be opened”<<endl; } else cout<<“File opened successfully”<<endl;

Page 18: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

Example:#include <fstream.h>void main(){ char name[50]; char sal[10]; char dept[30]; ifstream inFile; inFile.open("myfile.txt"); if(!inFile) { cout<<"Can’t open input file"<<endl; } while(!inFile.eof()) { inFile>>name>>sal>>dept; cout<<name<<"\t“<<sal<<“\t”<<dept<<endl; } inFile.close();} //end of main

Page 19: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

Output of the Program

Name Salary Department Omer 20000 Exam Ali 40000 Faculty Rashid 60000 Faculty

Page 20: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

Output File Handling

• Creation of a new file on the disk and writing data in it. or • Open an existing file and overwrite it in such a manner that

all old information is lost from it and new information is stored.

or • Open an existing file and append it in the end or• Open an existing file and modify it from anywhere.

Page 21: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

Cont…

• We can use the previous options when opening the file.

• open(filename,mode)

• The first argument is the name of the file, second argument will the mode of the file.

Page 22: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

Cont…..

• Syntax myFile.open(“myFile.txt”, ios::in);

or myFile.open(“myFile.txt”);

/* The second argument associated myFile stream object with “myFile.txt” for input. */

// There are different modes available

Page 23: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

File output: Appending#include <fstream>#include<iostream>

using namespace std;

void main()

{ cout<<"creating a file"<<endl; ofstream afile("test1.dat"); cout<<"writing to file.."<<endl; afile<<"these are test data";

} //end of file

Page 24: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

ios :: in open for reading (default for ifstream)ios :: out open for writing (default for ofstream)ios :: app start writing at end of file (APPend)ios :: ate start reading or writing at EOF of file (ATEnd)ios :: trunc truncate file to zero length if it exists (TRUNCate)ios :: nocreate error when opening if file does not already existios :: noreplace error when opening for output if file already existsios :: binary open file in binary (not text) mode

List of File Handling Modes

Page 25: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

25

Cont…

Mode Meaning

in Open a file/stream for extraction (input)

out Open a file/stream for insertion

(output)

App Append rather than truncate an existing file. Each insertion (output) will be written to end of the file.

trunc Discard the file contents if exists (similar to default behavior

ate Opens the file without truncating, but allows data to be written anywhere in the file.

binary Treat the file as binary rather than text. A binary file has data stored in internal formats, rather than readable text.

Page 26: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

Important……

• If a file is opened with ios::out mode, a new file is created. However if the file already exists, its contents will be deleted and get empty unless you write something to it.

Page 27: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

Example 2

main()

{

ofstream outFile;

outFile.open(“myFileOut.txt”,ios::out);

if(!outFile)

{

cout<<“ cannot open file”<<endl;

}

outFile.close();

}

Page 28: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

Try yourself…..

Write a program, which reads an input file of employee’s i.e. employeein.txt”. Add the salary of each employee by 200, and write the result in new file “ employeeout.txt”??

Page 29: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

get( )

• “>>” sign is not enough• get( ) function is used to get a character from the file.• The last character in the file is EOF, defined in header file.• E.g char c; while((c=inFile.get( ) !=EOF) { //do all the processing outFile.put(c); }

Page 30: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

Why get( )

• >> does not read the new line character where as the get( ) function reads each character as it is typed.

• If we need to make copy of the file then get( ) function must be used.

Page 31: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

put( )

• put( ) function writes a character including new line feed to the file.

Page 32: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

Think…….

What if we want to write/read a whole line to file instead of writing character or words. After all the processing speed now is day is quite high?

Page 33: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

getLine()

• Two functions– getLine() for input file stream– putLine() for output file stream

// char name[100]; int maxChar=100; int stopchar=‘o’; inFile.getLine(name,maxChar,stopchar);

myfile.getline (char *s, int n, char delim);

Character array delimiter

Numbers of characters to

be read

Page 34: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

Try yourself…..

• Write a program which reads a file using the getLine() function and display it on the screen?

Page 35: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

fail()

• A call to open can be unsuccessful for a number of reasons.

• A member function of ifstream and ofstream named fail can be used to test whether or not a stream operation has failed.

• It take no arguments and returns a bool.• Syntax:

– in_stream.fail( );

Page 36: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

Cont…Example: in_stream.open(“stuff.dat”); if (in_stream.fail()){ cout<<“input file opening failed.\n”; exit();

//to use this function include #include <cstdlib>

}

Page 37: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

isspace()

• The function isspace() returns true if its argument is a whitespace character else returns false.

• Whitespace are all the characters that are displayed as blank space on the screen, including the blank character, the tab character, and the new-line character ’\n’.

Page 38: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

Example:The following program will read the sentence terminatewith the period and echo the string with all whitespacecharacters replace with the symbol “_”.

char next;do{ cin.get(next); if(isspace(next)) cout<<‘_’; else cout<<next; } while (next !=‘.’);

Page 39: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

Try it yourself !!!!!!

Write a program that creates the output file “myoutput.txt” that is identical to the file“myoriginal.txt” except that all theoccurrences of ‘C’ are replace by “C++”.

Page 40: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

Random Access Files

• Discuss how to access the files randomly, forward and backward.

• Current position inside the file.• Concept of file position ( Pointer into the file)• tellg( ) and tellp( )----functions for

determining the file pointer position.

Page 41: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

Position in a File

• Assume that a file stream myfile is opened for reading .

• Myfile.tellg( ) gives us the current get position of the file pointer.

• It returns a whole number of type long, which is the position of the next character to be read from that file.

• tellp() function is used to determine the next position to write a character while writing into a file. It also returns a long number.

Page 42: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

Setting the Position

• How to move forward and backward within the file????

• seekg( ) and seekp( ) functions• seekg( )--- takes us to certain position to start

reading.• seekp( )---> leads the position to write into.• Both functions require an argument of type long to

let them know the number of bytes to move forward or backward. (positive and negative number)

Page 43: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

filePtr.seekg ( long Num , ios :: origin ) ;filePtr.seekg ( long Num , ios :: origin ) ;

Number of characters to move to

Starting point

Setting the Position

seekg ( 10L , ios :: beg ) ;seekg ( 10L , ios :: beg ) ;seekg (10L , ios :: cur ) ;seekg (10L , ios :: cur ) ;

seekg ( 10L , ios :: end ) ;seekg ( 10L , ios :: end ) ;

Page 44: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

Example:--)• aFile.seekg(10L, ios::beg) //move 10 bytes forward from the beginning of the file.• aFile.seekg(20L, ios::cur) // move 20 bytes in the forward direction starting from current

position (where current position can be obtained by using tellg( ) function.

• aFile.seekg(-10L,ios::cur) // move 10 bytes in the backward direction from the current

position• aFile.seekg(-100, ios::end) // move 100 bytes in backward direction from the end of the

file.

Page 45: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

Think and Apply…..

• Try to move the file pointer beyond the end of the file and before the beginning of the file and observe the behavior…….

Page 46: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

Example 1#include<fstream.h>main ( ){

int length ; ifstream inFile ( “myFile.txt” ) ; inFile.seekg ( 0L , ios :: end ) ; length = inFile.tellg ( ) ;

}It will tell you Length of the file

Page 47: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

Name city Date-of-Birth : : :

Jamil Ahmed Sukkur 10-10-1982 : : :

File

Rawalpindi

Very tricky if you want to write at the middle of the file

Page 48: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

Merge Method

This is a text data And needs

Original file Empty file

To be replaced NOT

For insertion in the middle of the file

1. The language does not impose any structure of the file, the file is just a bits and bytes for C++

2. For easiness1. Use serial number2. Use sorted files

Page 49: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

get ( ) and put ( ) character in a file

myInputFile.get ( c ) ;myOutputFile.put ( c ) ;

Page 50: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

read ( ) and write ( ) Functions

read ( char *buff , int count ) ;

write ( char *buff , int count ) ;

Area in memoryNumber of bytes to

be read

Area in memoryNumber of bytes to

be written

Page 51: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

char str [ 10000 ] ;myInputFile.read ( str , 10000 ) ;myOuputFile.write ( str , 10000 ) ;

Example 3

1. Read 10000 bytes from the file into str2. Write 10000 bytes to a file from str

Page 52: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

Example 2This is an Apple

This is a Sample

Page 53: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

Example 2:This program firstly writes a string into a file and then replaces it partially.

main(){ long pos; ofstream outfile; outfile.open(“test.txt”); outfile.write(“this is an apple”,16);

//write the string in the file pos=outfile.tellp();

//get the file pointer position outfile.seekp(pos-7);

// move 7 positions backward outfile.close(); }

Page 54: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

Try it !!!!!!!!

• Write a program that read the contents from “myfile1.txt” and copies the contents in reverse order in “outputfile.txt”……..

(Hint:---Make use of seekg function)

Page 55: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

HINTS:-)afile.seekg(0L, ios::end);afile.seekg(-1L, ios::end);//set the position of the cursor to the last

character of the file

while(afile){ cout<<afile.tellg()<<endl; afile.get(c); Ofile.put(c); afile.seekg(-2L,ios::cur);

//set the position of the cursor to the one character before the current position

}

Page 56: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

fstream

fstream myFile ( “Sample.txt” , ios :: in | ios :: out ) ;

Page 57: “After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more

Example:- Try to understand by yourself

fstream rfile;main(){char rchar;rfile.open(“myfile.txt”,ios::in||ios::out)if(!rfile){ cout<<“error opening file”;}for(rchar=‘A’;rchar<=‘Z’;rchar++){ rfile<<rchar; }rfile.seekg(8L, ios::beg);rfile>>rchar;cout<<“the 8th char is”<<rchar;rfile.seekg(-16L, ios::end);rfile>>rchar;cout<<“ the 16th character from the end”<<rchar;rfile.close();}