You are on page 1of 74

File Handling in C ++

Presented by :
Er. …………………
Assistant Professor
Applied Science(CSE)
Chandigarh University
Gharuan (Mohali).
1. INTRODUCTION
 Computer programs are associated to work with files as it
helps in storing data & information permanently.
 File - itself a bunch of bytes stored on some storage devices.
 In C++ this is achieved through a component header file
called fstream.h
 The I/O library manages two aspects- as interface and for
transfer of data.
 The library predefine a set of operations for all file related
handling through certain classes.
The fstream.h header file
A stream is a general term used to name flow of data.
Streams act as an interface between files and programs.
A Stream is sequence of bytes.
They represent as a sequence of bytes and deals with the
flow of data.
Every stream is associated with a class having member
functions and operations for a particular kind of data flow.

File  Program ( Input stream) - reads


Program  File (Output stream) – write

All designed into fstream.h and hence needs to be


included in all file handling programs.
Diagrammatically as shown in next slide
2. File Handling Classes
Hierarchy Diagram
3. FUNCTIONS OF FILE STREAM CLASSES
1. filebuf – It sets the buffer to read and write, it contains
close() and open() member functions on it.
2. fstreambase – this is the base class for fstream and,
ifstream and ofstream classes. therefore it provides the
common function to these classes. It also contains open()
and close() functions.
3. ifstream – Being input class it provides input operations it
inherits the functions get( ), getline( ), read( ), and random
access functions seekg( ) and tellg( ) functions.
4. ofstream – Being output class it provides output
operations it inherits put( ), write( ) and random access
functions seekp( ) and tellp( ) functions.
5. fstream – it is an i/o class stream, it provides simultaneous
input and output operations.
4. File TYPES
A File can be stored in two ways
Text File
Binary File

Text Files : Stores information in ASCII characters. In text file each


line of text is terminated by with special character known as EOL
(End of Line) In text file some translations takes place when this EOL
character is read or written.
Binary File: it contains the information in the same format as it is
held in the memory. In binary file there is no delimiter for a line.
Also no translation occur in binary file. As a result binary files are
faster and easier for program to read and write.
5. File modes
WHAT IS FILE MODE?
The File Mode describes how a file is to be used ; to read
from it, write to it, to append and so on
Syntax
Stream_object.open(“filename”,mode);
File Modes
ios::out: It open file in output mode (i.e write mode) and
place the file pointer in beginning, if file already exist it will
overwrite the file.
ios::in It open file in input mode(read mode) and permit
reading from the file.
File modes
ios::app It open the file in write mode, and place file pointer
at the end of file i.e to add new contents and retains previous
contents. If file does not exist it will create a new file.
ios::ate It open the file in write or read mode, and place file
pointer at the end of file i.e input/ output operations can
performed anywhere in the file.
ios::trunc It truncates the existing file (empties the file).
ios::nocreate If file does not exist this file mode ensures
that no file is created and open() fails.
 ios::noreplace If file does not exist, a new file gets created
but if the file already exists, the open() fails.
ios::binary Opens a file in binary mode.
6 .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.

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

12
7. 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.

13
Figure 1

14
Figure 2

15
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

16
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”);

17
Program
// 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 object
char 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";
}
18
Program Output with Example Input

Enter the name of a file you wish to open


or create: mystuff.dat [Enter]
The file mystuff.dat was opened.

19
Table

File Type Default Open Mode


ofstream The file is opened for output only. (Information may be
written to the file, but not read from the file.) If the file
does not exist, it is created. If the file already exists, its
contents are deleted (the file is truncated).
ifstream The file is opened for input only. (Information may be
read from the file, but not written to it.) The file’s
contents will be read from its beginning. If the file does
not exist, the open function fails.

20
Table
File Mode Flag Meaning
ios::app Append mode. If the file already exists, its
contents are preserved and all output is
written to the end of the file. By default, this
flag causes the file to be created if it does
not exist.
ios::ate If the file already exists, the program goes
directly to the end of it. Output may be
written anywhere in the file.
ios::binary Binary mode. When a file is opened in
binary mode, information is written to or
read from it in pure binary format. (The
default mode is text.)
ios::in Input mode. Information will be read from
the file. If the file does not exist, it will not
be created and the open function will fail.

21
Table continued
File Mode Meaning
Flag
ios::nocreate If the file does not already exist, this flag
will cause the open function to fail. (The file
will not be created.)
ios::noreplace If the file already exists, this flag will cause
the open function to fail. (The existing file
will not be opened.)
ios::out Output mode. Information will be written to
the file. By default, the file’s contents will
be deleted if it already exists.
ios::trunc If the file already exists, its contents will be
deleted (truncated). This is the default
mode used by ios::out.

22
Opening a File at Declaration
fstream dataFile(“names.dat”, ios::in | ios::out);

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

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

24
Program Output with Example Input

The file names.dat was opened.

25
Closing a File
A File is closed by disconnecting it with the stream it is
associated with. The close( ) function is used to accomplish
this task.
Syntax:
Stream_object.close( );

Example :
fout.close();
Program
// 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();
}
27
Program Output

File was created successfully.


Now closing the file.

28
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 !”

29
Program
// 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;
}

30
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";
}

31
Program Screen Output

File opened successfully.


Now writing information to the file.
Done.

Output to File demofile.txt


Jones
Smith
Willis
Davis

32
Figure 12-3

33
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();
} 34
Output to File demofile.txt

Jones
Smith
Willis
Davis

35
Steps To Create A File
1. Declare an object of the desired file stream class(ifstream,
ofstream, or fstream)

2. Open the required file to be processed using constructor or


open function.

3. Process the file.

4. Close the file stream using the object of file stream.


eof ( ) Function
This function determines the end-of-file by returning true(non-
zero) for end of file otherwise returning false(zero).

Syntax

Stream_object.eof( );

Example :
fout.eof( );
Text File Functions
get() – read a single character from text file and store in a
buffer.

e.g file.get(ch);

put() - writing a single character in textfile

e.g. file.put(ch);

getline() - read a line of text from text file store in a buffer.


e.g file.getline(s,80);

We can also use file>>ch for reading and file<<ch writing


in text file. But >> operator does not accept white spaces.
Program to create a text file using strings I/O

1. #include<fstream.h> //header file for file operations


2. void main()
3. {
4. char s[80], ch;
5. ofstream file(“myfile.txt”); //open myfile.txt in default
output mode
6. do
7. { cout<<”\n enter line of text”;
8. gets(s); //standard input
9. file<<s; // write in a file myfile.txt
10. cout<<”\n more input y/n”;
11. cin>>ch;
12. }while(ch!=’n’||ch!=’N’);
13. file.close();
14. } //end of main
Program to read content of ‘myfile.txt’ and display it
on monitor.

1. #include<fstream.h> //header file for file operations


2. void main()
3. {
4. char ch;
5. ifstream file(“myfile.txt”); //open myfile.txt in default input
mode
6. while(file)
7. { file.get(ch) // read a
8. character from text file ‘
9. myfile.txt’
10. cout<<ch; // write a character in text file ‘myfile.txt ‘
11. }
12. file.close();
13. } //end of main
1. Write a function in C++ to count the number of uppercase alphabets
present in a text file “BOOK.txt”

2. Write a function in C++ to count the number of alphabets present in a


text file “BOOK.txt”

3. Write a function in C++ to count the number of digits present in a text


file “BOOK.txt”

4. Write a function in C++ to count the number of white spaces present


in a text file “BOOK.txt”

5. Write a function in C++ to count the number of vowels present in a


text file “BOOK.txt”

6. Assume a text file “Test.txt” is already created. Using this file, write a
function to create three files “LOWER.TXT” which contains all the
lowercase vowels and “UPPER.TXT” which contains all the uppercase
vowels and “DIGIT.TXT” which contains all digits.
Binary File Functions
read( )- read a block of binary data or reads a fixed number of
bytes from the specified stream and store in a buffer.

Syntax : Stream_object.read((char *)& Object, sizeof(Object));

e.g file.read((char *)&s, sizeof(s));

write( ) – write a block of binary data or writes fixed number


of bytes from a specific memory location to the specified
stream.

Syntax : Stream_object.write((char *)& Object, sizeof(Object));

e.g file.write((char *)&s, sizeof(s));


Binary File Functions
Note: Both functions take two arguments.

• The first is the address of variable, and the second is the


length of that variable in bytes. The address of variable must
be type cast to type char*(pointer to character type)

• The data written to a file using write( ) can only be read


accurately using read( ).
Program to create a binary file ‘student.dat’ using structure.
1. #include<fstream.h>
2. struct student
3. {
4. char name[15];
5. float percent;
6. };
7. void main()
8. {
9. ofstream fout;
10. char ch;
11. fout.open(“student.dat”, ios::out | ios:: binary);
12. clrscr();
13. student s;
14. if(!fout)
15. {
16. cout<<“File can’t be opened”;
17. exit(0);
18. }
19. do
20. { cout<<”\n
21. enter name of student”;
22. gets(s);
23. cout<<”\n enter percentage”;
24. cin>>percent;
25. fout.write((char *)&s,sizeof(s)); // writing a record in a
student.dat file
26. cout<<”\n more record y/n”;
27. cin>>ch;
28. }while(ch!=’n’ || ch!=’N’);
29. fout.close();
30. }
Program to read a binary file ‘student.dat’ display records
on monitor.
1. #include<fstream.h>
2. struct student
3. {
4. char name[15];
5. float percent;
6. };
7. void main()
8. {
9. ifstream fin;
10. student s;
11. fin.open(“student.dat”,ios::in | ios:: binary);
12. fin.read((char *) &s, sizeof(student)); //read a record from
file ‘student.dat’
CONTD....
13. while(file)
14. {
15. cout<<s.name;
16. cout<<“\n has the percent: ”<<s.percent;
17. fin.read((char *) &s, sizeof(student));
18. }
19. fin.close();
20. }
QNO 4 ( C ) Write a function in c++ to search for details
(Phoneno and Calls) of those Phones which have more
than 800 calls from binary file “phones.dat”. Assuming
that this binary file contains records/ objects of class
Phone, which is defined below. CBSE 2012

class Phone
{
Char Phoneno[10]; int Calls;
public:
void Get() {gets(Phoneno); cin>>Calls;}
void Billing() { cout<<Phoneno<< “#”<<Calls<<endl;}
int GetCalls() {return Calls;}
};
Ans :
void Search()
{
Phone P;
fstream fin;
fin.open( “Phone.dat”, ios::binary| ios::in);
while(fin.read((char *)&P, sizeof(P)))
{
if(p.GetCalls() >800)
p.Billing();
}
Fin.close(); //ignore
}};
Write a function in C++ to add new objects at the bottom of a
binary file “STUDENT.DAT”, assuming the binary file is
containing the objects of the following class.

class STUD
{
int Rno;
char Name[20];
public:
void Enter()
{cin>>Rno;gets(Name);}
void Display(){cout<<Rno<<Name<<endl;}
};
Ans.
void searchbook(int bookno)
{ifstream ifile(“BOOK.DAT”,ios::in|ios::binary);
if(!ifile)
{cout<<”could not open BOOK.DAT file”; exit(-1);}
else
{BOOK b; int found=0;
while(ifile.read((char *)&b, sizeof(b)))
{if(b.RBno()==bookno)
{b.Display(); found=1; break;}
}
if(! found)
cout<<”record is not found “;
ifile.close();
}
}
Given a binary file PHONE.DAT, containing records of the
following class type
class Phonlist
{
char name[20];
char address[30];
char areacode[5];
char Phoneno[15];
public:
void Register()
void Show();
void CheckCode(char AC[])
{return(strcmp(areacode,AC);
};
Write a function TRANSFER( ) in C++, that would copy all
those records which are having areacode as “DEL” from
PHONE.DAT to PHONBACK.DAT.
Ans
void TRANSFER()
{
fstream File1,File2;
Phonelist P;
File1.open(“PHONE.DAT”, ios::binary|ios::in);
File2.open(“PHONEBACK.DAT”, ios::binary|ios::OUT)
while(File1.read((char *)&P, sizeof(P)))
{ if( p.CheckCode( “DEL”))
File2.write((char *)&P,sizeof(P)); }
File1.close();
File2.close();
}
File Pointer
The file pointer indicates the position in the file at which the
next input/output is to occur.

Moving the file pointer in a file for various operations viz


modification, deletion , searching etc. Following functions are
used
seekg(): It places the file pointer to the specified position in
input mode of file.
e.g file.seekg(p,ios::beg); or
file.seekg(-p,ios::end), or
file.seekg(p,ios::cur)
i.e to move to p byte position from beginning, end or current
position.
File Pointer
seekp(): It places the file pointer to the specified position in
output mode of file.
e.g file.seekp(p,ios::beg); or file.seekp(-p,ios::end), or
file.seekp(p,ios::cur)
i.e to move to p byte position from beginning, end or current
position.

tellg(): This function returns the current working position of the


file pointer in the input mode.
e.g int p=file.tellg();

tellp(): This function returns the current working position of the


file pointer in the output mode.
e.f int p=file.tellp();
4(a) Observe the program segment carefully and answer
the question that follows:

class stock
{
int Ino, Qty; Char Item[20];
public:
void Enter() { cin>>Ino; gets(Item); cin>>Qty;}
void issue(int Q) { Qty+=0;}
void Purchase(int Q) {Qty-=Q;}
int GetIno() { return Ino;}
};
void PurchaseItem(int Pino, int PQty)
{ fstream File;
File.open(“stock.dat”, ios::binary|ios::in|ios::out);
Stock s;
int success=0;
while(success= = 0 && File.read((char *)&s,sizeof(s)))
{
If(Pino= = ss.GetIno())
{
s.Purchase(PQty);
_______________________ // statement 1
_______________________ // statement 2
Success++;
}
}
if (success = =1)
cout<< “Purchase Updated”<<endl;
else
cout<< “Wrong Item No”<<endl;
File.close() ;
}
Ans
i) Statement 1 to position the file pointer to the appropriate
place so that the data updation is done for the required item.

File.seekp(File.tellg()-sizeof(stock);
OR
File.seekp(-sizeof(stock),ios::cur);

ii) Staement 2 to perform write operation so that the updation


is done in the binary file.

File.write((char *)&s, sizeof(s)); OR


File.write((char *)&s, sizeof(stock));
Random Access Files
• Random Access means non-sequentially
accessing informaiton in a file.
Figure 12-11

60
Table
Mode Flag Description

ios::beg The offset is calculated from


the beginning of the file.
ios::end The offset is calculated from
the end of the file.
ios::cur The offset is calculated from
the current position.

61
Table
Statement How it Affects the Read/Write Position
File.seekp(32L, ios::beg); Sets the write position to the 33rd byte
(byte 32) from the beginning of the file.
file.seekp(-10L, ios::end); Sets the write position to the 11th byte
(byte 10) from the end of the file.
file.seekp(120L, ios::cur); Sets the write position to the 121st byte
(byte 120) from the current position.
file.seekg(2L, ios::beg); Sets the read position to the 3rd byte
(byte 2) from the beginning of the file.
file.seekg(-100L, ios::end); Sets the read position to the 101st byte
(byte 100) from the end of the file.
file.seekg(40L, ios::cur); Sets the read position to the 41st byte
(byte 40) from the current position.
file.seekg(0L, ios::end); Sets the read position to the end of the
file.

62
Program
// 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;

63
Program continues

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

64
Program Screen Output

Byte 5 from beginning: f


Byte 10 from end: q
Byte 3 from current: u

65
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.

66
Program
// 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;

67
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();
}

68
Program Output with Example Input

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

69
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);

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

// Declaration of Invtry structure


struct Invtry
{
char desc[31];
int qty;
float price;
};

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

71
Program continues

// Now write the blank records


for (int count = 0; count < 5; count++)
{
cout << "Now writing record " << count << endl;
inventory.write((char *)&record, sizeof(record));
}
inventory.close();
}

72
Program Screen Output

Now writing record 0


Now writing record 1
Now writing record 2
Now writing record 3
Now writing record 4

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

// Declaration of Invtry structure


struct Invtry
{
char desc[31];
int qty;
float price;
};

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

74
Thanks……..

You might also like