starting out with c++, 3 rd edition basic file operations in c++ dr. ahmed telba

247
Starting Out with C++, 3 rd Edition Basic file operations in C+ + Dr. Ahmed Telba

Upload: dorthy-horn

Post on 14-Dec-2015

217 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Basic file operations in C++

Dr. Ahmed Telba

Page 2: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

2

Chapter – File Operations

Page 3: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

3

12.1 What is a File?

• A file is a collection on information, usually stored on a computer’s disk. Information can be saved to files and then later reused.

Page 4: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

4

12.2 File Names

• All files are assigned a name that is used for identification purposes by the operating system and the user.

Page 5: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

5

Table 12-1File Name and Extension File Contents

M Y P R O G .B A S BASIC program

M E N U .B A T DOS Batch File

IN S T A L L .D O C Documentation File

C R U N C H .E X E Executable File

B O B .H T M L HTML (Hypertext Markup Language) File

3 D M O D E L .JA V A Java program or applet

IN V E N T .O B J Object File

P R O G 1 .P R J Borland C++ Project File

A N S I.S Y S System Device Driver

R E A D M E .T X T Text File

Page 6: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

6

12.3 Focus on Software Engineering: The Process of Using a File

• Using a file in a program is a simple three-step process– The file must be opened. If the file does not yet

exits, opening it means creating it.– Information is then saved to the file, read from

the file, or both.– When the program is finished using the file, the

file must be closed.

Page 7: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

7

Figure 12-1

Page 8: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

8

Figure 12-2

Page 9: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

9

12.4 Setting Up a Program for File Input/Output

• Before file I/O can be performed, a C++ program must be set up properly.

• File access requires the inclusion of fstream.h

Page 10: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

10

12.5 Opening a File

• Before data can be written to or read from a file, the file must be opened.

ifstream inputFile;

inputFile.open(“customer.dat”);

Page 11: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

11

Program 12-1// This program demonstrates the declaration of an fstream// object and the opening of a file.#include <iostream.h> #include <fstream.h>

void main(void){

fstream dataFile; // Declare file stream objectchar fileName[81];cout << "Enter the name of a file you wish to open\n";cout << "or create: ";cin.getline(fileName, 81);dataFile.open(fileName, ios::out);cout << "The file " << fileName << " was opened.\n";

}

Page 12: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

12

Program Output with Example Input

Enter the name of a file you wish to openor create: mystuff.dat [Enter]The file mystuff.dat was opened.

Page 13: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

13

Table 12-3

File Type Default Open Mode

o fs tre a m The file is opened for output only. (Information may bewritten to the file, but not read from the file.) If the filedoes not exist, it is created. If the file already exists, itscontents are deleted (the file is truncated).

ifs tre a m The file is opened for input only. (Information may beread from the file, but not written to it.) The file’scontents will be read from its beginning. If the file doesnot exist, the open function fails.

Page 14: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

14

Table 12-4File Mode Flag Meaning

io s ::ap p Append mode. If the file already exists, itscontents are preserved and all output iswritten to the end of the file. By default, thisflag causes the file to be created if it doesnot exist.

io s ::a te If the file already exists, the program goesdirectly to the end of it. Output may bewritten anywhere in the file.

io s ::b in a ry Binary mode. When a file is opened inbinary mode, information is written to orread from it in pure binary format. (Thedefault mode is text.)

io s ::in Input mode. Information will be read fromthe file. If the file does not exist, it will notbe created and the open function will fail.

Page 15: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

15

Table 12-4 continued

File ModeFlag

Meaning

io s ::n o c rea te If the file does not already exist, this flagwill cause the open function to fail. (The filewill not be created.)

io s ::n o rep lace If the file already exists, this flag will causethe open function to fail. (The existing filewill not be opened.)

io s ::o u t Output mode. Information will be written tothe file. By default, the file’s contents willbe deleted if it already exists.

io s ::tru n c If the file already exists, its contents will bedeleted (truncated). This is the defaultmode used by ios::out.

Page 16: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

16

Opening a File at Declaration

fstream dataFile(“names.dat”, ios::in | ios::out);

Page 17: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

17

Program 12-2

// This program demonstrates the opening of a file at the// time the file stream object is declared.#include <iostream.h>#include <fstream.h>

main( ){

fstream dataFile("names.txt", ios::in | ios::out);cout << "The file names.dat was opened.\n";

system("PAUSE");}

Page 18: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

18

Program Output with Example Input

The file names.dat was opened.

Page 19: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

19

Testing for Open Errors

dataFile.open(“cust.txt”, ios::in);

if (!dataFile)

{

cout << “Error opening file.\n”;

}

Page 20: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

20

Another way to Test for Open Errors

dataFile.open(“cust.dat”, ios::in);

if (dataFile.fail())

{

cout << “Error opening file.\n”;

}

Page 21: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

21

12.6 Closing a File

• A file should be closed when a program is finished using it.

Page 22: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

// writing on a text file

• // writing on a text file• #include <iostream>• #include <fstream>• using namespace std;

• int main () {• ofstream myfile ("example.txt");• if (myfile.is_open())• {• myfile << "This is a new file created in cpp.\n";• myfile << "This is another line.\n";• myfile.close();• }• else cout << "Unable to open file";• system("pause");• return 0;• }

Page 23: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

// reading a text file

• // reading a text file• #include <iostream>• #include <fstream>• #include <string>• using namespace std;

• int main () {• string line;• ifstream myfile ("example.txt");• if (myfile.is_open())• {• while ( getline (myfile,line) )• {• cout << line << endl;• }• myfile.close();• }

• else cout << "Unable to open file"; • system("pause");• return 0;• }

Page 24: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

file operations in C++• #include <fstream>

• using namespace std;

• int main ()

• { ofstream myfile;

• myfile.open ("example22.txt");

• myfile << "Writing this to a file.\n";

• myfile<<"Hope fine”" << endl;

• myfile<<"this frist file ”" << endl;

• myfile.close();

• system("pause");

• return 0; }Slide 6- 24

Page 25: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

• #include <fstream>

• #include <iostream>

• using namespace std;

• int main()

• { char FirstName[30], LastName[30];

• int Age;

• char FileName[20];

• cout << "Enter First Name: ";

• cin >> FirstName;

• cout << "Enter Last Name: ";

• cin >> LastName;

• cout << "Enter Age: ";

• cin >> Age;

• cout << "\nEnter the name of the file you want to create: ";

• cin >> FileName;

• ofstream Students(FileName, ios::out);

• Students << FirstName << "\n" << LastName << "\n" << Age;

• cout << "\n\n";

• system("pause");

• return 0;

• }

Slide 6- 25

Page 26: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

• // basic file operations• #include <iostream>• #include <fstream>• using namespace std;

• int main () {• ofstream myfile;• myfile.open ("example.txt");• myfile << "Writing this to a file.\n";• myfile.close();• system("pause");• return 0;• }

Slide 6- 26

Page 27: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Write to file

• #include<iostream.h>• #include <fstream.h>• int main()• { ofstream fout;• fout.open("D:\\firstExa.txt");• fout << "Asalamualikom hope fine .\n"• << "WELCOME TO GE 211 FILE SECTION PROGRAM\n"• << "HOPE TO DO WELL IN SECOND MEDTERM EXAM\

n";• fout.close();• system("pause");• }

Page 28: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

• //Write the odd number in file• #include<iostream.h>• #include <fstream.h>• int main()• { ofstream fout;• fout.open("D:\\firstExa.txt");• int i,j;• for(i=2;i<30;i+=2)• fout<<i<<"\t";• fout.close();• system("pause");• }

Page 29: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

• // print in file Even number 1:30• #include<iostream.h>• #include <fstream.h>• int main()• { ofstream fout;• fout.open("D:\\firstExa.txt");• int i,j;• for(i=1;i<30;i+=2)• fout<<i<<"\t";• fout.close();• system("pause");• }

Page 30: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

• #include<iostream.h>• #include <fstream.h>• main()• {ofstream fout;• fout.open("D:\\ffffff.txt");• float i,j,m,sum;• j=3;• sum=0;• for(i=1;i<=100;i++){• m=(i*i)/(j*j);• j=j+2;• sum=sum+m;}• cout<<"seque="<<sum<<endl;• fout<<"seque="<<sum<<endl;• fout.close();• system("pause");}

Page 31: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

• //write equation for this series • #include<iostream.h>• main()• {• int i,j,m,n,sum;• sum=0;• cin>>n;• for(i=1 ;i<=n ;i++)• {• m=i*i;• sum=sum+m; } • cout<< "seque="<<sum<< endl;• system("pause");• }

Page 32: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

• #include<iostream.h>• #include <fstream.h>• #include<cmath>• main()• {• float i,m,n,b,a,y,x,s;• y=0;• b=2;• cout<<"enter the last power of\n";• cin>>n;• cout<<"enter the volue of(x)\n";• cin>>s;• for(i=1;i<=n;i++){• x=pow(s,i);• a=pow(b,i);• m=x/a;• y=y+m;• }• cout<<"y= "<<y;• system("pause");• }

Page 33: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

• #include<iostream.h>• #include <fstream.h>• #include<cmath>• main()• {ofstream fout;• fout.open("D:\\UUUU.txt");

• float i,m,n,b,a,y,x,s;• y=0;• b=2;• cout<<"enter the last power of\n";• cin>>n;• cout<<"enter the volue of(x)\n";• cin>>s;• for(i=1;i<=n;i++){• x=pow(s,i);• a=pow(b,i);• m=x/a;• y=y+m;• }• cout<<"y= "<<y;• fout<<"y= "<<y;• fout.close();• system("pause");• }

Page 34: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

• //Fenonci seris • #include<iostream.h>• #include <fstream.h>• main()• {ofstream fout;• fout.open("D:\\finoncy.txt");• int i,s,b,d ;• s=0;• d=1;• for(i=0;i<20;i++)• {• b=s;• s=d;• d=s+b;• fout<<d<<"\t";• }• fout.close();• system("pause");}

Page 35: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

• //write to file • #include<iostream.h>• #include <fstream.h>• main()• {• ofstream fout;• fout.open("D:\\Seris.txt");

• int i,j,m,n,sum;• sum=0;• cin>>n;• for(i=1 ;i<=n ;i++)• {• m=i*i;• sum=sum+m; } • fout<< "seque="<<sum<< endl;• fout.close();• system("pause");• }

Page 36: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Read from file

• #include <fstream.h>• #include <iostream.h>• main()• { char array [80];• ifstream fin;• fin.open("D:\\firstExa.txt");• while(!fin.eof())• {fin.getline(array,80);• cout<<array<<endl;}• fin.close();• system("pause"); }

Page 37: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

FLAGES IN FILE

• FLAGES IN FILE

Page 38: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Write in binary file

• ofstream fout ;

• fout.open("file path",iostream family

• fout.write((char*)& data ,sizeo(data);

Page 39: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Binary form

• #include<iostream.h>• #include <fstream.h>• main()• { int Array[80],i;• for(i=0;i<10;i++)• cin>> Array[i];• ofstream fout;• fout.open("D:\\ahmed.bin",ios::binary);• fout .write((char *) & Array , sizeof(Array));• fout.close();• system("pause");• }

Page 40: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

• // writing on a text file• #include <iostream>• #include <fstream>• using namespace std;

• int main () {• ofstream myfile ("example.txt");• if (myfile.is_open())• {• myfile << "This is a line.\n";• myfile << "This is another line.\n";• myfile.close();• }• else cout << "Unable to open file";• system("pause");• return 0;• }

Slide 6- 40

Page 41: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

• // reading a text file

• #include <iostream>

• #include <fstream>

• #include <string>

• using namespace std;

• int main () {

• string line;

• ifstream myfile ("example.txt");

• if (myfile.is_open())

• {

• while ( myfile.good() )

• {

• getline (myfile,line);

• cout << line << endl;

• }

• myfile.close();

• }

• else cout << "Unable to open file";

• system("pause");

• return 0;

• }

Slide 6- 41

Page 42: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 42

I/O Streams

• I/O refers to program input and output

– Input is delivered to your program via a stream object

– Input can be from• The keyboard

• A file

– Output is delivered to the output device via a streamobject

– Output can be to • The screen

• A file

Page 43: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Using fout

Slide 6- 43

• #include <iostream>

• #include <fstream>

• #include <cstdlib>

• using namespace std;

• int main (int aaa,char *avg[])

• {

• ofstream fout ("my_out.txt");

• fout<<" Assalamualikom Hope fine" << endl;

• fout<<"Please tray good in second exam this frist file " << endl;

• system("pause");

• return 0;}

Page 44: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Write in file • #include <fstream>• #include <iostream>• using namespace std;

• int main( )• {

• //cout<<"Exam1\n";• // ifstream ;// read• // ofstream ;// write• // fstream;//read &write• ofstream myfile;• myfile.open("kkkk.txt");• myfile<< "Exam1 is ok\n";• myfile<< "please tray good in second exam";• myfile.close();• system("pause");• return 0;• }

Page 45: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Using fstream

• #include <fstream>• #include <iostream>• using namespace std;

• int main( )• {

• /*cout<<"Exam1\n";• // ifstream ;// read• // ofstream ;// write• // fstream;//read &write*/• fstream myfile;• myfile.open("kkkk.txt",ios ::out);

• //myfile<< "Exam1 is ok\n";• myfile<< "please tray good in second exam****************";• //cout<<myfile.rdbuf();• myfile.close();

• system("pause");• return 0;• }

Page 46: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Using app

• #include <fstream>• #include <iostream>• using namespace std;

• int main( )• {

• /*cout<<"Exam1\n";• ifstream ;// read• ofstream ;// write• fstream;//read &write*/• fstream myfile;• myfile.open("kkkk.txt",ios ::out|ios::app);

• //myfile<< "Exam1 is ok\n";• myfile<< "please tray good in second exam****************\n";• //cout<<myfile.rdbuf();• myfile.close();

• system("pause");• return 0;• }

Page 47: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Read from file• #include <fstream>• #include <iostream>• using namespace std;

• int main( )• {

• /*cout<<"Exam1\n";• ifstream ;// read• ofstream ;// write• fstream;//read &write*/• ifstream myfile;• myfile.open("kkkk.txt");

• //myfile<< "Exam1 is ok\n";• //myfile<< "please tray good in second exam";• cout<<myfile.rdbuf();• myfile.close();

• system("pause");• return 0;• }

Page 48: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Input &Output with files

• Input / Output with files

• C++ provides the following classes to perform output and input of characters to/from files:

• ofstream: Stream class to write on files

• ifstream: Stream class to read from files

• fstream: Stream class to both read and write from/to files.

Page 49: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

• // basic file operations• #include <iostream>• #include <fstream>• using namespace std;

• int main () {• ofstream myfile;• myfile.open ("example.txt");• myfile << "Writing this to a file.\n";• myfile.close();• return 0;• }

Page 50: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

class default mode parameter

ofstream ios::out

ifstream ios::in

fstream ios::in | ios::out

ofstream myfile;myfile.open ("example.bin", ios::out | ios::app | ios::binary);

Page 51: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Basic file operations

• // basic file operations• #include <iostream>• #include <fstream>• //#include <ifstream>• //#include <ofstream>

• using namespace std;

• int main () {• ofstream myfile;• myfile.open ("XXX.txt");• myfile << "**Writing this to a file.\n";• myfile << "****Writing this to a file.\n";• myfile << "*********Writing this to a file.\n";• myfile.close();• system("PAUSE");• return 0;• }

Page 52: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Basic file operations

• #include <iostream>• #include <fstream>• using namespace std;

• int main (int argc, char *arvg[ ]) • {• ofstream fout("XXX.txt");• fout << "**Writing this to a file.\n";• fout << "****Writing this to a file.\n";• fout << "*********Writing this to a file.\n";• system("PAUSE");• return EXIT_SUCCESS;• }

Page 53: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

FILE IN C++

ios::in Open for input operations.

ios::out Open for output operations.

ios::binary Open in binary mode.

ios::ateSet the initial position at the end of the file.If this flag is not set to any value, the initial position is the beginning of the file.

ios::app

All output operations are performed at the end of the file, appending the content to the current content of the file. This flag can only be used in streams open for output-only operations.

ios::truncIf the file opened for output operations already existed before, its previous content is deleted and replaced by the new one.

Page 54: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

• // writing on a text file• #include <iostream>• #include <fstream>• using namespace std;

• int main () {• ofstream myfile ("example.txt");• if (myfile.is_open())• {• myfile << "This is a line.\n";• myfile << "This is another line.\n";• myfile.close();• }• else cout << "Unable to open file";• return 0;• }

Page 55: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

• Open a file

• The first operation generally performed on an object of one of these classes is to associate it to a real file. This procedure is known as to open a file.

• An open file is represented within a program by a stream object (an instantiation of one of these classes, in the previous example this was myfile) and any input or output operation performed on this stream object will be applied to the physical file associated to it.

• In order to open a file with a stream object we use its member function open():

• open (filename, mode);

• Where filename is a null-terminated character sequence of type const char * (the same type that string literals have) representing the name of the file to be opened, and mode is an optional parameter with a combination of the following flags:

Page 56: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Page 57: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Page 58: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

• IOS :: IN OPEN FILE FOR READ

Page 59: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Page 60: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Page 61: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

61

Program 12-3// This program demonstrates the close function.#include <iostream.h>#include <fstream.h>void main(void){

fstream dataFile;dataFile.open("testfile.txt", ios::out);if (!dataFile){

cout << "File open error!" << endl;return;

}cout << "File was created successfully.\n";cout << "Now closing the file.\n";dataFile.close();

}

Page 62: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

62

Program Output

File was created successfully.Now closing the file.

Page 63: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

63

12.7 Using << to Write Information to a File

• The stream insertion operator (<<) may be used to write information to a file.

outputFile << “I love C++ programming !”

Page 64: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

64

Program 12-4// This program uses the << operator to write information

to a file.#include <iostream.h>#include <fstream.h>

void main(void){

fstream dataFile;char line[81];

dataFile.open("demofile.txt", ios::out);if (!dataFile){

cout << "File open error!" << endl;return;

}

Page 65: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

65

Program continues

cout << "File opened successfully.\n";cout << "Now writing information to the file.\n";dataFile << "Jones\n";dataFile << "Smith\n";dataFile << "Willis\n";dataFile << "Davis\n";dataFile.close();cout << "Done.\n";

}

Page 66: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

66

Program Screen Output

File opened successfully.Now writing information to the file.Done.

Output to File demofile.txtJonesSmithWillisDavis

Page 67: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

67

Figure 12-3

Page 68: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

68

Program 12-5// This program writes information to a file, closes the file,// then reopens it and appends more information.#include <iostream.h>#include <fstream.h>void main(void){

fstream dataFile;

dataFile.open("demofile.txt", ios::out);dataFile << "Jones\n";dataFile << "Smith\n";dataFile.close();dataFile.open("demofile.txt", ios::app);dataFile << "Willis\n";dataFile << "Davis\n";dataFile.close();

}

Page 69: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

69

Output to File demofile.txt

JonesSmithWillisDavis

Page 70: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

70

12.8 File Output Formatting

• File output may be formatted the same way as screen output.

Page 71: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

71

Program 12-6// This program uses the precision member function of a// file stream object to format file output.#include <iostream.h>#include <fstream.h>

void main(void){

fstream dataFile;float num = 123.456;dataFile.open("numfile.txt", ios::out);if (!dataFile){

cout << "File open error!" << endl;return;

}

Page 72: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

72

Program continues

dataFile << num << endl;dataFile.precision(5);dataFile << num << endl;dataFile.precision(4);dataFile << num << endl;dataFile.precision(3);dataFile << num << endl;

}

Page 73: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

73

Contents of File numfile.txt

123.456123.46123.5124

Page 74: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

74

Program 12-7#include <iostream.h> #include <fstream.h>#include <iomanip.h>void main(void){ fstream outFile("table.txt", ios::out);

int nums[3][3] = { 2897, 5, 837, 34, 7, 1623, 390, 3456, 12 };// Write the three rows of numbersfor (int row = 0; row < 3; row++){

for (int col = 0; col < 3; col++){

outFile << setw(4) << nums[row][col] << " ";}outFile << endl;

}outFile.close();

}

Page 75: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

75

Contents of File TABLE.TXT

2897 5 837 34 7 1623 390 3456 12

Page 76: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

76

Figure 12-6

Page 77: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

77

12.9 Using >> to Read Information from a File

• The stream extraction operator (>>) may be used to read information from a file.

Page 78: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

78

Program 12-8

// This program uses the >> operator to read information from a file.

#include <iostream.h> #include <fstream.h>

void main(void){

fstream dataFile;char name[81];dataFile.open("demofile.txt", ios::in);if (!dataFile){

cout << "File open error!" << endl;return;

}cout << "File opened successfully.\n";cout << "Now reading information from the file.\n\n";

Page 79: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

79

Program continues

for (int count = 0; count < 4; count++){

dataFile >> name;cout << name << endl;

}dataFile.close();cout << "\nDone.\n";

}

Page 80: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

80

Program Screen Output

File opened successfully.Now reading information from the file.

JonesSmithWillisDavis

Done.

Page 81: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

81

12.10 Detecting the End of a File

• The eof() member function reports when the end of a file has been encountered.

if (inFile.eof())

inFile.close();

Page 82: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

82

Program 12-9// This program uses the file stream object's eof() member// function to detect the end of the file.#include <iostream.h> #include <fstream.h>void main(void){

fstream dataFile;char name[81];dataFile.open("demofile.txt", ios::in);if (!dataFile){

cout << "File open error!" << endl;return;

}cout << "File opened successfully.\n";cout << "Now reading information from the file.\n\n";

Page 83: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

83

Program continues

dataFile >> name; // Read first name from the filewhile (!dataFile.eof()){

cout << name << endl;dataFile >> name;

}dataFile.close();cout << "\nDone.\n";

}

Page 84: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

84

Program Screen Output

File opened successfully.Now reading information from the file.

JonesSmithWillisDavisDone.

Page 85: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

85

Note on eof()

• In C++, “end of file” doesn’t mean the program is at the last piece of information in the file, but beyond it. The eof() function returns true when there is no more information to be read.

Page 86: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

86

12.11 Passing File Stream Objects to Functions• File stream objects may be passed by reference to

functions.bool openFileIn(fstream &file, char name[51]){ bool status;

file.open(name, ios::in); if (file.fail()) status = false; else status = true; return status;}

Page 87: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

87

12.12 More Detailed Error Testing

• All stream objects have error state bits that indicate the condition of the stream.

Page 88: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

88

Table 12-5

Bit Description

io s::eo fb it Set when the end of an input stream isencountered.

io s ::fa ilb it Set when an attempted operation has failed.

io s ::h a rd fa il Set when an unrecoverable error has occurred.

io s ::b a d b it Set when an invalid operation has beenattempted.

io s ::g o o d b it Set when all the flags above are not set.Indicates the stream is in good condition.

Page 89: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

89

Table 12-6Function Description

eo f() Returns true (non-zero) if the eofbit flag is set,otherwise returns false.

fa il() Returns true (non-zero) if the failbit or hardfailflags are set, otherwise returns false.

b ad () Returns true (non-zero) if the badbit flag is set,otherwise returns false.

g o o d () Returns true (non-zero) if the goodbit flag isset, otherwise returns false.

c lea r() When called with no arguments, clears all theflags listed above. Can also be called with aspecific flag as an argument.

Page 90: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

90

Program 12-11// This program demonstrates the return value of the stream// object error testing member functions.#include <iostream.h> #include <fstream.h>// Function prototypevoid showState(fstream &);

void main(void){

fstream testFile("stuff.dat", ios::out);if (testFile.fail()){

cout << "cannot open the file.\n";return;

}

Page 91: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

91

Program continues

int num = 10;cout << "Writing to the file.\n";testFile << num; // Write the integer to testFileshowState(testFile);testFile.close(); // Close the filetestFile.open("stuff.dat", ios::in); // Open for inputif (testFile.fail()){

cout << "cannot open the file.\n";return;

}

Page 92: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

92

Program continues

cout << "Reading from the file.\n";testFile >> num; // Read the only number in the fileshowState(testFile);cout << "Forcing a bad read operation.\n";testFile >> num; // Force an invalid read operationshowState(testFile);testFile.close(); // Close the file

}

// Definition of function ShowState. This function uses// an fstream reference as its parameter. The return values of// the eof(), fail(), bad(), and good() member functions are // displayed. The clear() function is called before the function// returns.

Page 93: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

93

Program continues

void showState(fstream &file){

cout << "File Status:\n";cout << " eof bit: " << file.eof() << endl;cout << " fail bit: " << file.fail() << endl;cout << " bad bit: " << file.bad() << endl;cout << " good bit: " << file.good() << endl;file.clear(); // Clear any bad bits

}

Page 94: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

94

Program OutputWriting to the file.File Status: eof bit: 0 fail bit: 0 bad bit: 0 good bit: 1Reading from the file.File Status: eof bit: 0 fail bit: 0 bad bit: 0 good bit: 1Forcing a bad read operation.File Status: eof bit: 1 fail bit: 2 bad bit: 0 good bit: 0

Page 95: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

95

12.13 Member Functions for Reading and Writing Files

• File stream objects have member functions for more specialized file reading and writing.

Page 96: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

96

Figure 12-8

Page 97: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

97

Program 12-12// This program uses the file stream object's eof() member// function to detect the end of the file.#include <iostream.h> #include <fstream.h>

void main(void){

fstream nameFile;char input[81];

nameFile.open("murphy.txt", ios::in);if (!nameFile){

cout << "File open error!" << endl;return;

}

Page 98: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

98

Program 12-12 (continued)

nameFile >> input;while (!nameFile.eof()){

cout << input;nameFile >> input;

}nameFile.close();

}

Page 99: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

99

Program Screen Output

JayneMurphy47JonesCircleAlmond,NC28702

Page 100: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

100

The getline Member Function

• dataFile.getline(str, 81, ‘\n’);str – This is the name of a character array, or a pointer to a

section of memory. The information read from the file will be stored here.

81 – This number is one greater than the maximum number of characters to be read. In this example, a maximum of 80 characters will be read.

‘\n’ – This is a delimiter character of your choice. If this delimiter is encountered, it will cause the function to stop reading before it has read the maximum number of characters. (This argument is optional. If it’s left our, ‘\n’ is the default.)

Page 101: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

101

Program 12-13// This program uses the file stream object's getline member// function to read a line of information from the file.

#include <iostream.h> #include <fstream.h>

void main(void){

fstream nameFile;char input[81];

nameFile.open("murphy.txt", ios::in);if (!nameFile){

cout << "File open error!" << endl;return;

}

Page 102: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

102

Program continues

nameFile.getline(input, 81); // use \n as a delimiterwhile (!nameFile.eof()){

cout << input << endl;nameFile.getline(input, 81); // use \n as a

delimiter}nameFile.close();

}

Page 103: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

103

Program Screen Output

Jayne Murphy47 Jones CircleAlmond, NC 28702

Page 104: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

104

Program 12-14// This file shows the getline function with a user-// specified delimiter.

#include <iostream.h> #include <fstream.h>void main(void){

fstream dataFile("names2.txt", ios::in);char input[81];

dataFile.getline(input, 81, '$');while (!dataFile.eof()){

cout << input << endl;dataFile.getline(input, 81, '$');

}dataFile.close();

}

Page 105: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

105

Program Output

Jayne Murphy47 Jones CircleAlmond, NC 28702

Bobbie Smith217 Halifax DriveCanton, NC 28716

Bill HammetPO Box 121

Springfield, NC 28357

Page 106: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

106

The get Member Function

inFile.get(ch);

Page 107: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

107

Program 12-15// This program asks the user for a file name. The file is // opened and its contents are displayed on the screen.#include <iostream.h> #include <fstream.h>

void main(void){

fstream file;char ch, fileName[51];cout << "Enter a file name: ";cin >> fileName;file.open(fileName, ios::in);if (!file){

cout << fileName << “ could not be opened.\n";return;

}

Page 108: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

108

Program continues

file.get(ch); // Get a characterwhile (!file.eof()){

cout << ch;file.get(ch); // Get another character

}file.close();

}

Page 109: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

109

The put Member Function

• outFile.put(ch);

Page 110: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

110

Program 12-16// This program demonstrates the put member function.#include <iostream.h> #include <fstream.h>

void main(void){ fstream dataFile("sentence.txt", ios::out);

char ch;

cout << "Type a sentence and be sure to end it with a ";cout << "period.\n";while (1){

cin.get(ch);dataFile.put(ch);if (ch == '.') break;

}dataFile.close();

}

Page 111: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

111

Program Screen Output with Example Input

Type a sentence and be sure to end it with aperiod.

I am on my way to becoming a great programmer. [Enter]

Resulting Contents of the File SENTENCE.TXT:

I am on my way to becoming a great programmer.

Page 112: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

112

12.14 Focus on Software Engineering: Working with Multiple Files

• It’s possible to have more than one file open at once in a program.

Page 113: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

113

Program 12-17// This program demonstrates reading from one file and writing// to a second file.#include <iostream.h> #include <fstream.h>#include <ctype.h> // Needed for the toupper function

void main(void){

ifstream inFile;ofstream outFile("out.txt");char fileName[81], ch, ch2;

cout << "Enter a file name: ";cin >> fileName;inFile.open(fileName);if (!inFile){

cout << "Cannot open " << fileName << endl;return;

}

Page 114: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

114

Program continuesinFile.get(ch); // Get a characer from file 1while (!inFile.eof()) // Test for end of file{

ch2 = toupper(ch); // Convert to uppercaseoutFile.put(ch2); // Write to file2

inFile.get(ch); // Get another character from file 1}inFile.close();outFile.close();cout << "File conversion done.\n";

}

Page 115: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

115

Program Screen Output with Example Input

Enter a file name: hownow.txt [Enter]

File conversion done.

Contents of hownow.txt:how now brown cow.

How Now?

Resulting Contents of out.txt:HOW NOW BROWN COW.

HOW NOW?

Page 116: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

116

12.15 Binary Files

• Binary files contain data that is unformatted, and not necessarily stored as ASCII text.file.open(“stuff.dat”, ios::out | ios::binary);

Page 117: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

117

Figure 12-9

Page 118: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

118

Figure 12-10

Page 119: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

119

Program 12-18// This program uses the write and read functions.#include <iostream.h> #include <fstream.h>

void main(void){

fstream file(“NUMS.DAT", ios::out | ios::binary);int buffer[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

cout << "Now writing the data to the file.\n";file.write((char*)buffer, sizeof(buffer));file.close();file.open("NUMS.DAT", ios::in); // Reopen the file.cout << "Now reading the data back into memory.\n";file.read((char*)buffer, sizeof(buffer));for (int count = 0; count < 10; count++)

cout << buffer[count] << " ";file.close();

}

Page 120: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

120

Program Screen Output

Now writing the data to the file.Now reading the data back into memory.

1 2 3 4 5 6 7 8 9 10

Page 121: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

121

12.16 Creating Records with Structures

• Structures may be used to store fixed-length records to a file.

struct Info{ char name[51]; int age; char address1[51]; char address2[51]; char phone[14];};

• Since structures can contain a mixture of data types, you should always use the ios::binary mode when opening a file to store them.

Page 122: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

122

Program 12-19// This program demonstrates the use of a structure variable to// store a record of information to a file.

#include <iostream.h> #include <fstream.h>#include <ctype.h> // for toupper

// Declare a structure for the record.struct Info{

char name[51];int age;char address1[51];char address2[51];char phone[14];

};

Page 123: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

123

Program continues

void main(void){

fstream people("people.dat", ios::out | ios::binary);Info person;char again;if (!people){

cout << "Error opening file. Program aborting.\n";return;

}

do{

cout << "Enter the following information about a ”<< "person:\n";

cout << "Name: ";

Page 124: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

124

Program continuescin.getline(person.name, 51);cout << "Age: ";cin >> person.age;cin.ignore(); // skip over remaining newline.cout << "Address line 1: ";cin.getline(person.address1, 51);cout << "Address line 2: ";cin.getline(person.address2, 51);cout << "Phone: ";cin.getline(person.phone, 14);people.write((char *)&person, sizeof(person));cout << "Do you want to enter another record? ";cin >> again;cin.ignore();

} while (toupper(again) == 'Y');people.close();

}

Page 125: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

125

Program Screen Output with Example InputEnter the following information about a person:Name: Charlie Baxter [Enter]Age: 42 [Enter]Address line 1: 67 Kennedy Bvd. [Enter]Address line 2: Perth, SC 38754 [Enter]Phone: (803)555-1234 [Enter]Do you want to enter another record? Y [Enter]Enter the following information about a person:Name: Merideth Murney [Enter]Age: 22 [Enter]Address line 1: 487 Lindsay Lane [Enter]Address line 2: Hazelwood, NC 28737 [Enter]Phone: (704)453-9999 [Enter]

Do you want to enter another record? N [Enter]

Page 126: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

126

12.17 Random Access Files

• Random Access means non-sequentially accessing informaiton in a file.

Figure 12-11

Page 127: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

127

Table 12-7

Mode Flag Description

io s ::b e g The offset is calculated fromthe beginning of the file.

io s ::en d The offset is calculated fromthe end of the file.

io s ::cu r The offset is calculated fromthe current position.

Page 128: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

128

Table 12-8

Statement How it Affects the Read/Write Position

F ile .see k p (3 2 L , io s ::b eg ); Sets the write position to the 33rd byte (byte 32) from the beginning of the file.

file .see k p (-1 0 L , io s ::en d ); Sets the write position to the 11th byte (byte 10) from the end of the file.

file .see k p (1 2 0 L , io s ::cu r) ; Sets the write position to the 121st byte (byte 120) from the current position.

file .see k g (2 L , io s ::b eg ); Sets the read position to the 3rd byte (byte 2) from the beginning of the file.

file .see k g (-1 0 0 L , io s ::en d ); Sets the read position to the 101st byte (byte 100) from the end of the file.

file .see k g (4 0 L , io s ::cu r); Sets the read position to the 41st byte (byte 40) from the current position.

file .see k g (0 L , io s ::en d ); Sets the read position to the end of the file.

Page 129: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

129

Program 12-21// This program demonstrates the seekg function.

#include <iostream.h> #include <fstream.h>

void main(void){

fstream file("letters.txt", ios::in);char ch;

file.seekg(5L, ios::beg);file.get(ch);cout << "Byte 5 from beginning: " << ch << endl;file.seekg(-10L, ios::end);file.get(ch);cout << "Byte 10 from end: " << ch << endl;

Page 130: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

130

Program continues

file.seekg(3L, ios::cur);file.get(ch);cout << "Byte 3 from current: " << ch << endl;file.close();

}

Page 131: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

131

Program Screen Output

Byte 5 from beginning: fByte 10 from end: q

Byte 3 from current: u

Page 132: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

132

The tellp and tellg Member Functions

• tellp returns a long integer that is the current byte number of the file’s write position.

• tellg returns a long integer that is the current byte number of the file’s read position.

Page 133: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

133

Program 12-23// This program demonstrates the tellg function.#include <iostream.h> #include <fstream.h>#include <ctype.h> // For toupper

void main(void){

fstream file("letters.txt", ios::in);long offset;char ch, again;

do{

cout << "Currently at position " << file.tellg() << endl;cout << "Enter an offset from the beginning of the file:

";cin >> offset;

Page 134: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

134

Program continues

file.seekg(offset, ios::beg);file.get(ch);cout << "Character read: " << ch << endl;cout << "Do it again? ";cin >> again;

} while (toupper(again) == 'Y');file.close();

}

Page 135: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

135

Program Output with Example Input

Currently at position 0Enter an offset from the beginning of the file: 5 [Enter]Character read: fDo it again? y [Enter]Currently at position 6Enter an offset from the beginning of the file: 0 [Enter]Character read: aDo it again? y [Enter]Currently at position 1Enter an offset from the beginning of the file: 20 [Enter]Character read: u

Do it again? n [Enter]

Page 136: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

136

12.18 Opening a File for Both Input and Output

• You may perform input and output on an fstream file without closing it and reopening it.

fstream file(“data.dat”, ios::in | ios::out);

Page 137: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

137

Program 12-24// This program sets up a file of blank inventory records.#include <iostream.h>#include <fstream.h>

// Declaration of Invtry structurestruct Invtry{

char desc[31];int qty;float price;

};

void main(void){

fstream inventory("invtry.dat", ios::out | ios::binary);Invtry record = { "", 0, 0.0 };

Page 138: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

138

Program continues

// Now write the blank recordsfor (int count = 0; count < 5; count++){

cout << "Now writing record " << count << endl;inventory.write((char *)&record, sizeof(record));

}inventory.close();

}

Page 139: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

139

Program Screen Output

Now writing record 0Now writing record 1Now writing record 2Now writing record 3

Now writing record 4

Page 140: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

140

Program 12-25// This program displays the contents of the inventory file.#include <iostream.h>#include <fstream.h>

// Declaration of Invtry structurestruct Invtry{

char desc[31];int qty;float price;

};

void main(void){

fstream inventory("invtry.dat", ios::in | ios::binary);Invtry record = { "", 0, 0.0 };

Page 141: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

141

Program continues

// Now read and display the recordsinventory.read((char *)&record, sizeof(record));while (!inventory.eof()){

cout << "Description: ";cout << record.desc << endl;cout << "Quantity: ";cout << record.qty << endl;cout << "Price: ";cout << record.price << endl << endl;inventory.read((char *)&record, sizeof(record));

}inventory.close();

}

Page 142: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

142

Here is the screen output of Program 12-25 if it is run immediately after Program 12-24 sets up the file of blank records.

Program Screen OutputDescription:Quantity: 0Price: 0.0Description:Quantity: 0Price: 0.0Description:Quantity: 0Price: 0.0Description:Quantity: 0Price: 0.0Description:Quantity: 0Price: 0.0

Page 143: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

143

Program 12-26// This program allows the user to edit a specific record in// the inventory file.#include <iostream.h>#include <fstream.h>

// Declaration of Invtry structurestruct Invtry{

char desc[31];int qty;float price;

};

void main(void){

Page 144: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

144

Program continues

fstream inventory("invtry.dat", ios::in | ios::out | ios::binary);Invtry record;long recNum;cout << "Which record do you want to edit?";cin >> recNum;inventory.seekg(recNum * sizeof(record), ios::beg);inventory.read((char *)&record, sizeof(record));cout << "Description: ";cout << record.desc << endl;cout << "Quantity: ";cout << record.qty << endl;cout << "Price: ";cout << record.price << endl;cout << "Enter the new data:\n";cout << "Description: ";

Page 145: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

145

Program continues

cin.ignore();cin.getline(record.desc, 31);cout << "Quantity: ";cin >> record.qty;cout << "Price: ";cin >> record.price;inventory.seekp(recNum * sizeof(record), ios::beg);inventory.write((char *)&record, sizeof(record));inventory.close();

}

Page 146: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

146

Program Screen Output with Example Input

Which record do you ant to edit? 2 [Enter]Description:Quantity: 0Price: 0.0Enter the new data:Description: Wrench [Enter]Quantity: 10 [Enter]

Price: 4.67 [Enter]

Page 147: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Page 148: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Chapter 6

I/O Streams as an Introduction to Objects and Classes

Page 149: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 149

Overview

6.1 Streams and Basic File I/O

6.2 Tools for Stream I/O

6.3 Character I/O

Page 150: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

6.1

Streams and Basic File I/O

Page 151: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 151

I/O Streams

• I/O refers to program input and output

– Input is delivered to your program via a stream object

– Input can be from• The keyboard

• A file

– Output is delivered to the output device via a streamobject

– Output can be to • The screen

• A file

Page 152: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 152

Objects

• Objects are special variables that– Have their own special-purpose functions– Set C++ apart from earlier programming

languages

Page 153: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 153

Streams and Basic File I/O

• Files for I/O are the same type of files used tostore programs

• A stream is a flow of data.

– Input stream: Data flows into the program• If input stream flows from keyboard, the program will

accept data from the keyboard

• If input stream flows from a file, the program will acceptdata from the file

– Output stream: Data flows out of the program• To the screen

• To a file

Page 154: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 154

cin And cout Streams

• cin– Input stream connected to the keyboard

• cout – Output stream connected to the screen

• cin and cout defined in the iostream library– Use include directive: #include <iostream>

• You can declare your own streams to use with

files.

Page 155: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 155

Why Use Files?

• Files allow you to store data permanently!

• Data output to a file lasts after the program ends

• An input file can be used over and over

– No typing of data again and again for testing

• Create a data file or read an output file at yourconvenience

• Files allow you to deal with larger data sets

Page 156: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 156

File I/O

• Reading from a file

– Taking input from a file

– Done from beginning to the end (for now)• No backing up to read something again (OK to start over)

• Just as done from the keyboard

• Writing to a file

– Sending output to a file

– Done from beginning to end (for now)• No backing up to write something again( OK to start over)

• Just as done to the screen

Page 157: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 157

Stream Variables

• Like other variables, a stream variable… – Must be declared before it can be used– Must be initialized before it contains valid data

• Initializing a stream means connecting it to a file

• The value of the stream variable can be thought of as the file it is connected to

– Can have its value changed• Changing a stream value means disconnecting from

one file and connecting to another

Page 158: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 158

Streams and Assignment

• A stream is a special kind of variable called an object

– Objects can use special functions to complete tasks

• Streams use special functions instead of the assignment operator to change values

Page 159: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 159

Declaring An Input-file Stream Variable

• Input-file streams are of type ifstream

• Type ifstream is defined in the fstream library

– You must use the include and using directives #include <fstream> using namespace std;

• Declare an input-file stream variable using ifstream in_stream;

Page 160: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 160

Declaring An Output-file Stream Variable

• Ouput-file streams of are type ofstream

• Type ofstream is defined in the fstream library

– You must use these include and using directives #include <fstream> using namespace std;

• Declare an input-file stream variable using ofstream out_stream;

Page 161: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 161

• Once a stream variable is declared, connect it toa file– Connecting a stream to a file is opening the file– Use the open function of the stream object

in_stream.open("infile.dat");

Period

File name on the disk

Double quotes

Connecting To A File

Page 162: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 162

Using The Input Stream

• Once connected to a file, the input-stream variable can be used to produce input just asyou would use cin with the extraction operator– Example:

int one_number, another_number; in_stream >> one_number >> another_number;

Page 163: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 163

Using The Output Stream

• An output-stream works similarly to the input-stream– ofstream out_stream;

out_stream.open("outfile.dat");

out_stream << "one number = " << one_number << "another number = " << another_number;

Page 164: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 164

External File Names

• An External File Name…

– Is the name for a file that the operating system uses• infile.dat and outfile.dat used in the previous examples

– Is the "real", on-the-disk, name for a file

– Needs to match the naming conventions on your system

– Usually only used in the stream's open statement

– Once open, referred to using the name of the stream connected to it.

Page 165: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

• After using a file, it should be closed

– This disconnects the stream from the file

– Close files to reduce the chance of a file being corrupted if the program terminates abnormally

• It is important to close an output file if your program later needs to read input from the output file

• The system will automatically close files if you forget as long as your program ends normally

Slide 6- 165

Display 6.1

Closing a File

Page 166: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 166

Objects

• An object is a variable that has functions and data associated with it– in_stream and out_stream each have a function

named open associated with them– in_stream and out_stream use different

versions of a function named open • One version of open is for input files• A different version of open is for output files

Page 167: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 167

Member Functions

• A member function is a function associated withan object– The open function is a member function of

in_stream in the previous examples– A different open function is a member function

of out_stream in the previous examples

Page 168: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 168

Objects and Member Function Names

• Objects of different types have different member functions

– Some of these member functions might have the same name

• Different objects of the same type have the same member functions

Page 169: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 169

Classes

• A type whose variables are objects, is a class

– ifstream is the type of the in_stream variable (object)

– ifstream is a class

– The class of an object determines its member functions

– Example: ifstream in_stream1, in_stream2;

• in_stream1.open and in_stream2.open are the samefunction but might have different arguments

Page 170: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 170

Class Member Functions

• Member functions of an object are the memberfunctions of its class

• The class determines the member functions ofthe object

– The class ifstream has an open function

– Every variable (object) declared of type ifstream has that open function

Page 171: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 171

Calling object

Dot operator

Member function

Calling a Member Function

• Calling a member function requires specifying the object containing the function

• The calling object is separated from the member function by the dot operator

• Example: in_stream.open("infile.dat");

Page 172: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 172

Member Function Calling Syntax

• Syntax for calling a member function:

Calling_object.Member_Function_Name(Argument_list);

Page 173: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 173

Errors On Opening Files

• Opening a file could fail for several reasons– Common reasons for open to fail include

• The file might not exist

• The name might be typed incorrectly

• May be no error message if the call to open fails– Program execution continues!

Page 174: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 174

Catching Stream Errors

• Member function fail, can be used to test the success of a stream operation– fail returns a boolean type (true or false)– fail returns true if the stream operation failed

Page 175: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 175

Halting Execution

• When a stream open function fails, it is generally best to stop the program

• The function exit, halts a program

– exit returns its argument to the operating system

– exit causes program execution to stop

– exit is NOT a member function

• Exit requires the include and using directives #include <cstdlib> using namespace std;

Page 176: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

• Immediately following the call to open, check that the operation was successful:

in_stream.open("stuff.dat"); if( in_stream.fail( ) ) { cout << "Input file opening failed.\n"; exit(1) ; }

Slide 6- 176

Display 6.2

Using fail and exit

Page 177: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 177

Techniques for File I/O

• When reading input from a file…

– Do not include prompts or echo the input• The lines cout << "Enter the number: ";

cin >> the_number; cout << "The number you

entered is " << the_number;become just one line

in_file >> the_number;

– The input file must contain exactly the data expected

Page 178: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

• Output examples so far create new files

– If the output file already contains data, that datais lost

• To append new output to the end an existing file

– use the constant ios::app defined in the iostream library: outStream.open("important.txt", ios::app);

– If the file does not exist, a new file will be created

Slide 6- 178

Display 6.3

Appending Data (optional)

Page 179: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 179

File Names as Input (optional)

• Program users can enter the name of a file to use for input or for output

• Program must use a variable that can hold multiple characters – A sequence of characters is called a string – Declaring a variable to hold a string of characters:

char file_name[16];• file_name is the name of a variable• Brackets enclose the maximum number of characters + 1 • The variable file_name contains up to 15 characters

Page 180: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

• char file_name[16];cout << "Enter the file_name ";cin >> file_name;ifstream in_stream;in_stream.open(file_name);if (in_stream.fail( ) ){ cout << "Input file opening failed.\n"; exit(1);}

Slide 6- 180

Display 6.4 (1)

Display 6.4 (2)

Using A Character String

Page 181: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 181

Section 6.1 Conclusion

• Can you

– Write a program that uses a stream called fin which will be connected to an input file and a stream calledfout which will be connected to an output file? Howdo you declare fin and fout? What include directive, if any, do you nee to place in yourprogram file?

– Name at least three member functions of an iostream object and give examples of usage of each?

Page 182: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

6.2

Tools for Streams I/O

Page 183: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 183

Tools for Stream I/O

• To control the format of the program's output – We use commands that determine such details as:

• The spaces between items• The number of digits after a decimal point• The numeric style: scientific notation for fixed point• Showing digits after a decimal point even if they are

zeroes• Showing plus signs in front of positive numbers• Left or right justifying numbers in a given space

Page 184: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 184

Formatting Output to Files

• Format output to the screen with: cout.setf(ios::fixed);

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

• Format output to a file using the out-file stream named out_stream with:

out_stream.setf(ios::fixed);out_stream.setf(ios::showpoint);

out_stream.precision(2);

Page 185: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 185

out_stream.precision(2);

• precision is a member function of output streams

– After out_stream.precision(2);Output of numbers with decimal points…

• will show a total of 2 significant digits 23. 2.2e7 2.2 6.9e-10.00069OR

• will show 2 digits after the decimal point23.56 2.26e7 2.21 0.69 0.69e-4

• Calls to precision apply only to the streamnamed in the call

Page 186: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 186

setf(ios::fixed);

• setf is a member function of output streams

– setf is an abbreviation for set flags• A flag is an instruction to do one of two options

• ios::fixed is a flag

– After out_stream.setf(ios::fixed);All further output of floating point numbers…

• Will be written in fixed-point notation, the way we normally expect to see numbers

• Calls to setf apply only to the stream named inthe call

Page 187: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

• After out_stream.setf(ios::showpoint);

Output of floating point numbers…• Will show the decimal point even if all digits after

thedecimal point are zeroes

Slide 6- 187

Display 6.5

setf(ios::showpoint);

Page 188: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 188

7 7

(ios::right) (ios::left)

Creating Space in Output

• The width function specifies the number of spaces for the next item

– Applies only to the next item of output

• Example: To print the digit 7 in four spaces use out_stream.width(4); out_stream << 7 << endl;

– Three of the spaces will be blank

Page 189: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 189

Not Enough Width?

• What if the argument for width is too small?– Such as specifying

cout.width(3); when the value to print is 3456.45

• The entire item is always output– If too few spaces are specified, as many more

spaces as needed are used

Page 190: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 190

Unsetting Flags

• Any flag that is set, may be unset

• Use the unsetf function– Example:

cout.unsetf(ios::showpos);

causes the program to stop printing plus signs on positive numbers

Page 191: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 191

Manipulators

• A manipulator is a function called in a nontraditional way– Manipulators in turn call member functions– Manipulators may or may not have arguments– Used after the insertion operator (<<) as if the

manipulator function call is an output item

Page 192: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 192

Two Spaces Four Spaces

The setw Manipulator

• setw does the same task as the member function width

– setw calls the width function to set spaces for output

• Example: cout << "Start" << setw(4) << 10 << setw(4) << setw(6) << 30;

produces: Start 10 20 30

Page 193: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 193

The setprecision Manipulator

• setprecision does the same task as the member function precision

• Example: cout.setf(ios::fixed); cout.setf(ios::showpoint); cout << "$" << setprecision(2)

<< 10.3 << endl<< "$" << 20.5 << endl;

produces: $10.30

$20.50– setprecision setting stays in effect until changed

Page 194: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 194

Manipulator Definitions

• The manipulators setw and setprecision are defined in the iomanip library– To use these manipulators, add these lines

#include <iomanip>using namespace std;

Page 195: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 195

Stream Names as Arguments

• Streams can be arguments to a function– The function's formal parameter for the stream

must be call-by-reference

• Example: void make_neat(ifstream& messy_file, ofstream& neat_file);

Page 196: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 196

The End of The File

• Input files used by a program may vary in length

– Programs may not be able to assume the numberof items in the file

• A way to know the end of the file is reached:

– The boolean expression (in_stream >> next)• Reads a value from in_stream and stores it in next

• True if a value can be read and stored in next

• False if there is not a value to be read (the end of the file)

Page 197: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 197

End of File Example

• To calculate the average of the numbers in a file– double next, sum = 0;

int count = 0; while(in_stream >> next) {

sum = sum + next; count++; }

double average = sum / count;

Page 198: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 198

Stream Arguments and Namespaces

• Using directives have been local to function definitions in the examples so far

• When parameter type names are in a namespace

– A using directive must be outside the function soC++ will understand the parameter type names suchas ifstream

• Easy solution is to place the using directive at thebeginning of the file

– Many experts do not approve as this does not allow using multiple namespaces with names in common

Page 199: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

• The program in Display 6.6…

– Takes input from rawdata.dat

– Writes output to the screen and to neat.dat• Formatting instructions are used to create a neater layout

• Numbers are written one per line in a field width of 12

• Each number is written with 5 digits after the decimal point

• Each number is written with a plus or minus sign

– Uses function make_neat that has formal parametersfor the input-file stream and output-file stream

Slide 6- 199

Display 6.6 (1) Display 6.6 (2) Display 6.6 (3)

Program Example

Page 200: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 200

Section 6.2 Conclusion

• Can you– Show the output produced when the following

line is executed?

cout << "*" << setw(3) << 12345 << "*" endl;

– Describe the effect of each of these flags?Ios::fixed ios::scientific ios::showpointios::right ios::right ios::showpos

Page 201: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

6.3

Character I/O

Page 202: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 202

Character I/O

• All data is input and output as characters

– Output of the number 10 is two characters '1' and '0'

– Input of the number 10 is also done as '1' and '0'

– Interpretation of 10 as the number 10 or as charactersdepends on the program

– Conversion between characters and numbers isusually automatic

Page 203: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 203

Low Level Character I/O

• Low level C++ functions for character I/O– Perform character input and output – Do not perform automatic conversions– Allow you to do input and output in anyway

youcan devise

Page 204: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 204

Member Function get

• Function get– Member function of every input stream– Reads one character from an input stream– Stores the character read in a variable of type

char, the single argument the function takes– Does not use the extraction operator (>>)

which performs some automatic work– Does not skip blanks

Page 205: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 205

Using get

• These lines use get to read a character and store it in the variable next_symbol

char next_symbol; cin.get(next_symbol);

– Any character will be read with these statements• Blank spaces too!

• '\n' too! (The newline character)

Page 206: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 206

get Syntax

• input_stream.get(char_variable);

• Examples: char next_symbol;cin.get(next_symbol);

ifstream in_stream;in_stream.open("infile.dat");in_stream.get(next_symbol);

Page 207: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 207

More About get

• Given this code: char c1, c2, c3;cin.get(c1);cin.get(c2);cin.get(c3);

and this input: AB CD

• c1 = 'A' c2 = 'B' c3 = '\n'– cin >> c1 >> c2 >> c3; would place 'C' in c3

(the ">>" operator skips the newline character)

Page 208: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 208

The End of The Line

• To read and echo a line of input– Look for '\n' at the end of the input line:

cout<<"Enter a line of input and I will " << "echo it.\n";

char symbol; do { cin.get(symbol); cout << symbol;

} while (symbol != '\n');– All characters, including '\n' will be output

Page 209: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 209

'\n ' vs "\n "

• '\n'– A value of type char– Can be stored in a variable of type char

• "\n"– A string containing only one character– Cannot be stored in a variable of type char

• In a cout-statement they produce the same result

Page 210: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 210

Member Function put

• Function put– Member function of every output stream– Requires one argument of type char– Places its argument of type char in the output

stream– Does not do allow you to do more than

previous output with the insertion operator and cout

Page 211: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 211

put Syntax

• Output_stream.put(Char_expression);

• Examples: cout.put(next_symbol); cout.put('a');

ofstream out_stream; out_stream.open("outfile.dat"); out_stream.put('Z');

Page 212: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 212

Member Function putback

• The putback member function places a character in the input stream

– putback is a member function of every input stream

– Useful when input continues until a specific characteris read, but you do not want to process the character

– Places its argument of type char in the input stream

– Character placed in the stream does not have tobe a character read from the stream

Page 213: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 213

putback Example

• The following code reads up to the first blank in the input stream fin, and writes the characters tothe file connected to the output stream fout– fin.get(next);

while (next != ' ') { fout.put(next); fin.get(next); } fin.putback(next);

– The blank space read to end the loop is put back into the input stream

Page 214: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 214

Program ExampleChecking Input

• Incorrect input can produce worthless output

• Use input functions that allow the user to re-enter input until it is correct, such as– Echoing the input and asking the user if it is

correct– If the input is not correct, allow the user to

enter the data again

Page 215: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 215

Checking Input: get_int

• The get_int function seen in Display 6.7obtains an integer value from the user

– get_int prompts the user, reads the input, and displaysthe input

– After displaying the input, get_int asks the user to confirm the number and reads the user's responseusing a variable of type character

– The process is repeated until the user indicates witha 'Y' or 'y' that the number entered is correct

Page 216: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

• The new_line function seen in Display 6.7 is called by the get_int function

– new_line reads all the characters remaining in the input line but does nothing with them, essentially discarding them

– new_line is used to discard what follows the first character of the the user's response to get_line's "Is that correct? (yes/no)"

• The newline character is discarded as well

Slide 6- 216

Display 6.7 (1)

Display 6.7 (2)

Checking Input: new_line

Page 217: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 217

Checking Input:Check for Yes or No?

• get_int continues to ask for a number until theuser responds 'Y' or 'y' using the do-while loop do {

// the loop body} while ((ans !='Y') &&(ans != 'y') )

• Why not use ((ans =='N') | | (ans == 'n') )?– User must enter a correct response to continue

a loop tested with ((ans =='N') | | (ans == 'n') )• What if they mis-typed "Bo" instead of "No"?

– User must enter a correct response to end the loop tested with ((ans !='Y') &&(ans != 'y') )

Page 218: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 218

Mixing cin >> and cin.get

• Be sure to deal with the '\n' that ends each input line if using cin >> and cin.get– "cin >>" reads up to the '\n'– The '\n' remains in the input stream– Using cin.get next will read the '\n'– The new_line function from Display 6.7 can

be used to clear the '\n'

Page 219: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 219

The Dialogue:Enter a number:21Now enter a letter:A

The Result:number = 21

symbol = '\n'

'\n' Example

• The Code: cout << "Enter a number:\n";int number;cin >> number;cout << "Now enter a letter:\n";char symbol;cin.get(symbol);

Page 220: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 220

A Fix To Remove '\n'

• cout << "Enter a number:\n";int number;cin >> number;cout << "Now enter a letter:\n";char symbol;cin >>symbol;

Page 221: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 221

Another '\n' Fix

• cout << "Enter a number:\n";int number;cin >> number;new_line( ); // From Display 6.7cout << "Now enter a letter:\n";char symbol;cin.get(symbol);

Page 222: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 222

Detecting the End of a File

• Member function eof detects the end of a file– Member function of every input-file stream– eof stands for end of file– eof returns a boolean value

• True when the end of the file has been reached• False when there is more data to read

– Normally used to determine when we are NOT at the end of the file

• Example: if ( ! in_stream.eof( ) )

Page 223: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 223

Using eof

• This loop reads each character, and writes it tothe screen

• in_stream.get(next);while (! in_stream.eof( ) )

{ cout << next; in_stream.get(next); }

• ( ! In_stream.eof( ) ) becomes false when the program reads past the last character in the file

Page 224: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 224

The End Of File Character

• End of a file is indicated by a special character

• in_stream.eof( ) is still true after the last character of data is read

• in_stream.eof( ) becomes false when the special end of file character is read

Page 225: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 225

How To Test End of File

• We have seen two methods– while ( in_stream >> next)– while ( ! in_stream.eof( ) )

• Which should be used?– In general, use eof when input is treated as text

and using a member function get to read input– In general, use the extraction operator method

when processing numeric data

Page 226: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

• The program of Display 6.8…

– Reads every character of file cad.dat and copies it tofile cplusad.dat except that every 'C' is changed to"C++" in cplusad.dat

– Preserves line breaks in cad.dat• get is used for input as the extraction operator would skip

line breaks

• get is used to preserve spaces as well

– Uses eof to test for end of file

Slide 6- 226

Display 6.8 (1)

Display 6.8 (2)

Program Example:Editing a Text File

Page 227: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 227

Character Functions

• Several predefined functions exist to facilitate working with characters

• The cctype library is required– #include <cctype>

using namespace std;

Page 228: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 228

The toupper Function

• toupper returns the argument's upper case character – toupper('a') returns 'A'– toupper('A') return 'A'

Page 229: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 229

toupper Returns An int

• Characters are actually stored as an integer assigned to the character

• toupper and tolower actually return the integerrepresenting the character

– cout << toupper('a'); //prints the integer for 'A'

– char c = toupper('a'); //places the integer for 'A' in ccout << c; //prints 'A'

– cout << static_cast<char>(toupper('a')); //works too

Page 230: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

• isspace returns true if the argument is whitespace– Whitespace is spaces, tabs, and newlines– isspace(' ') returns true– Example: if (isspace(next) )

cout << '-'; else

cout << next;– Prints a '-' if next contains a space, tab, or

newline character• See more character functions in

Slide 6- 230

Display 6.9 (1)

Display 6.9 (2)

The isspace Function

Page 231: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 231

Section 6.3 Conclusion

• Can you– Write code that will read a line of text and echo

the line with all the uppercase letters deleted?

– Describe two methods to detect the end of an input file:

– Describe whitespace?

Page 232: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Slide 6- 232

Chapter 6 -- End

Page 233: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Display 6.1

Slide 6- 233

Back Next

Page 234: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Display 6.2

Slide 6- 234

Back Next

Page 235: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Display 6.3

Slide 6- 235

Back Next

Page 236: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Display 6.4 (1/2)

Slide 6- 236

Back Next

Page 237: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Display 6.4 (2/2)

Slide 6- 237

Back Next

Page 238: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Display 6.5

Slide 6- 238

Back Next

Page 239: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Display 6.6 (1/3)

Slide 6- 239

Back Next

Page 240: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Display 6.6 (2/3)

Slide 6- 240

Back Next

Page 241: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Display 6.6(3/3)

Slide 6- 241

Back Next

Page 242: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Display 6.7 (1/2)

Slide 6- 242

Back Next

Page 243: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Display 6.7 (2/2)

Slide 6- 243

Back Next

Page 244: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Display 6.8 (1/2)

Slide 6- 244

NextBack

Page 245: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Display 6.8 (2/2)

Slide 6- 245

Back Next

Page 246: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Display 6.9(1/2)

Slide 6- 246

Back Next

Page 247: Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

Starting Out with C++, 3rd Edition

Display 6.9 (2/2)

Slide 6- 247

Back Next