File Handling Basics in Programming
File Handling Basics in Programming
Computer Programming
Chapter 3
File Handling (Management)
§ Revision on I/O Stream
§ Basics of File Management
Ø Types of file (Text file and Binary file)
Ø File Stream
§ File Manipulation Process
Ø Opening and closing files
Chapter 8 3
Revision on I/O Stream (2/3)
§ The primary source of program I/O data are INPUT devices and
OUTPUT devices, mainly keyboard and computer screen (monitor).
§ The flow of data between I/O devices and a program is called
Standard I/O Stream.
§ The two main standard I/O streams are
Ø cin - Input from stream object connected to keyboard
Ø cout - Output to stream object connected to screen
4
Chapter 8
Revision on I/O Stream (3/3)
§ What is the draw backs of standard I/O streams?
Ø The data is Input from the keyboard where as the output data
is printed to the screen where an Ordinary variable is used.
Ø The ordinary variables (even records and arrays) are kept in
main memory which is temporary storage.
Ø Moreover, the memory is limited in size (storage capacity).
Ø As a result, the Input/output data would be lost as soon as you
exit from the program.
§ Solution
Ø Store data on the secondary storage permanently.
Ø Input/output data can be stored on secondary storage as a file
(records).
Chapter 8 5
Basics of File Management (1/8)
What is file?
§ File is a collection of data or a set of characters or maybe a text
or a program.
§ File is stored permanently on secondary storage (disk) and can
be retrieved when needed.
Why File?
ü Used to store data relatively in permanent form, on hard disk
or other form of secondary storage.
ü Files can hold huge amounts of data if need be.
Chapter 8 6
Basics of File Management (2/8)
File Handling (Management)
§ File handling is a mechanism to store the output of a program in a
file and perform various operations on it.
§ The flow of data between file and program is referred as File
stream.
Ø File Input Stream – reads data from disk file to the program
Ø File output Stream – writes data to the disk file from the program.
Chapter 8 7
Basics of File Management (3/8)
§ Each file stream is associated with a particular class, which
contains member functions and definitions for dealing with a
particular kind of data flow.
§ The I/O system of C++ provides the following stream classes which
have access to standard I/O stream objects and file functions.
8
Chapter 8
Basics of File Management (4/8)
§ The main class stream that used for file manipulation are
Ø ifstream – provides input operations on files
Ø ofstream – provides output operations on files
Ø fstream – supports both input and output operations on files.
- allow simultaneously to read from and write to a file
9
Chapter 8
Basics of File Management (5/8)
Types of File
§ There are two types of file which the streams are linked to.
Chapter 8 10
Basics of File Management (6/8)
(a) Binary File
§ A sequence of bytes with a one-to-one correspondence to those in
the external device
Ø The number of bytes written (or read) is the same as the number on the
external device
§ No character translations required
Ø Data is stored to disk in the same form in which it is represented in main
memory.
Ø As a result, saving data in binary format is faster and takes less space
§ Human unreadable
Ø If you ever try to edit a binary file for example containing numbers you
will see that the numbers appear as nonsense characters.
Ø Do not normally use anything to separate the data into lines.
§ Binary format data can not easily be transferred from one
computer to another due to variations in the internal
representation of the data fro computer to computer.
Chapter 8 11
Basics of File Management (7/8)
Text File
Binary File
Chapter 8 12
Basics of File Management (8/8)
Text File Stream Vs. Binary File Stream
Text Stream Binary Stream
Write out separately each of the Write a whole record data to the file
pieces of data about a given record at once
Readable by an editor Not readable by editor directly
The main way of opening, reading &
The main way of opening, reading & writing is using the file stream object
writing is using the file stream object with
with ü write() function to write to the file
ü Insertion operator (>>) for reading the entire record
ü Extraction operator (<<) for writing ü Read() function to read from a file
a whole record
Require the ios::binary offset (file
It is the default file format mode) to open the file for binary read
and write
Chapter 8 13
File Manipulation Process (1/13)
§ Before actually starting to use and manipulate files, it is important
to discuss the steps to be followed in order to process files.
§ Here are the steps that need to be followed in order to perform
successful file operations though your program
Ø Declaration of file stream object
Ø Opening a file (attach file stream with a specific file)
Ø Check for successful opening of the file (optional)
Ø Perform File Read/Write Operations
Ø Closing a file
Note
Ø To perform file read and write (I/O), it is mandatory to include the
header file fstream.h which defines several classes and functions.
Chapter 8 14
File Manipulation Process (2/13)
(a) Declaration of File Stream Object
§ In order to process file through a program, logical file must be
created on the RAM.
§ This logical file is nothing but a file having file data type.
§ Syntax: object
File_Stream File_Stream_Object;
Ø Where the “File_Stream” refers to either of the three file stream
classes ifstream, ofstream, fstream.
Ø On the other hand the “File_Stream_Object” is referring to any
valid identifier
§ Once the file stream object is created, you can use it to open a file
and perform various writing and reading operation.
Chapter 8 15
File Manipulation Process (3/13)
(b) Opening a file
§ In order to perform read and write operations on the file through a
program, the file should be opened.
§ Opening a file attaches the stream link to a specific file.
§ Syntax:
File_Stream_Object.Open(“FileName”, File modes) ;
Where
Ø “File Name” - refers to the name of file on which we are going to
perform file operations. It should be provided with it’s full path
(where the file is located) and file extension
Ø “File modes” – specifies for what purpose the file is opened and
it can be a single mode or multiple file modes.
Note - the File stream object creation and opening a file can be merged and
performed in a single statement (steps), see next slide.
Chapter 8 16
File Manipulation Process (4/13)
File Modes These are file attributes (modes) for the various kinds of
file opening operation
Mode Description
ios::app Write all output to the end of the file
ü Open a file for output and move to the end of the file (normally used to
ios::ate append data to a file).
ü Data can be written anywhere in the file.
ios::binary Cause the file to be opened in binary mode.
ios::in Open a file for input
ios::out Open a file for output
ios::nocreate If the file does not exist, the open operation fails.
ios::noreplace If the file exists, the open operation fails.
ü Discard the file's content if it exists
ios:trunc
ü This is also the default action of ios::out
Ios::beg From beginning of the file
Ios::end From the end of the file
Ios::cur From the current file pointer position
17
Chapter 8
File Manipulation Process (5/13)
Example 1: Stream Object Creation and file opening
Ø Declaring appropriate file stream
fstream file; //file stream object both for reading and writing
Ø Opening a file using stream object with open() function
[Link] (“[Link]”, ios::in | ios::out);
//opening a file for both reading and writing
Chapter 8 23
File Manipulation Process (11/13)
(e) Closing a file
§ Why do we need to close a file?
Ø To make the stream object free and so it can be used with more
than one file.
Ø To avoid a logical error that will occur because of not closing an
opened file
§ How to close a file? Using two possible methods
Ø Using close() function
[Link]();
e.g. [Link]();
Ø Using clear() function
[Link]();
e.g. [Link]();
§ In both cases the file that opened using the “inf” file stream will be closed
Chapter 8 24
File Manipulation Process (12/13)
The prototype of file read and write functions
Function Prototype and Syntax (1st and 2nd line respectively)
istream & get( char & ch );
[Link]( ch );
1. get()
istream &get (char *buf, int num, char delim = '\n');
[Link]((char*)&buf, sizeof(buf));
ostream & put ( char ch);
2. Put()
[Link](‘a’);
istream & getline ( char *buf, int num, char delim ='\n');
3. getline()
[Link]((char*)&buf, sizeof(buf));
istream & read ( unsigned char * buf, int num );
4. read()
[Link]((char*)&buf, sizeof(buf));
ostream & write ( const unsigned char * buf, int num );
5. write()
[Link](“Hello there”,11);
Note: infile – input file stream, outfile - output file stream, ch – character variable, buffer – string variable
Chapter 8 25
File Manipulation Process (13/13)
Description of the functions
Function Description
Read a character or one line string from the associated stream and
1. get() puts the value in ch or buff, and returns a reference to the stream
Write a character stored on ch to the stream and returns a
2. Put() reference to the stream.
Read a one line string from the associated stream and puts the
3. getline() value in buff, and returns a reference to the stream
ü Reads num bytes from the associated stream, and puts them in
a memory buffer (pointed to by buf).
4. read() ü If the end-of-file is reached before num characters have been
read, then read () stops and puts the read character on the
memory buffer
Writes num bytes to the associated stream from the memory buffer
5. write() (pointed to by buf).
Chapter 8 26
Stream state functions (1/2)
§ The stream state member functions give the information status like
end of the file has been reached or file open failure and so on.
Function Description
ü Returns true if a reading or writing operation fails.
bad() ü For example in the case that we try to write to a file that is not open for
writing or if the device where we try to write has no space left.
Returns true in the same cases as bad(), but also in the case that a format
fail() error happens, like when an alphabetical character is extracted when we are
trying to read an integer number.
eof() Returns true if a file open for reading has reached the end.
It is the most generic state flag: It returns false in the same cases in which
good() calling any of the previous functions would return true.
is_open() It used to check either the file is opened or not.
Used to obtain next character in the input stream without removing it from
Peek() that stream
Ignore() Reads and discards characters until either num characters have been ignored
putback () Operates in the reveres of peek()
Chapter 8 27
Stream state functions (2/2)
File stream state offsets
§ eofbit - 1 when end-of-file is encountered; 0 otherwise
§ Openbit - 1 when a is opened successfully; 0 otherwise
§ failbit - 1 when a (possibly) nonfatal I/O error has occurred; 0 otherwise
§ badbit - 1 when a fatal I/O error has occurred; 0 otherwise
#include<fstream.h>
For example int main()
{
Ifstream f1;
[Link](“sam”);
while(![Link]()){
[Link](ch);
}
}
Chapter 8 28
File Random Access (1/5)
§ Basically there are two types of file access: sequential and random.
(a) Sequential access.
Ø With this type of file access one must read the data in order, much like
with a tape, whether the data is really stored on tape or not.
Chapter 8 29
File Random Access (2/5)
File Pointers
§ Each file object has two integer values associated with it
Ø get pointer
Ø put pointer
§ The values of the pointers specify the byte number in the file where
reading or writing will take place.
§ By default
Ø reading pointer is set at the beginning
Ø writing pointer is set at the end (when the file open is opened in
ios::app or ios::ate mode)
Chapter 8 30
File Random Access (3/5)
Random Access
§ Allow you to read from and write to an arbitrary location in the file.
§ The seekg() and tellg() functions allow you to set and examine the
get pointer where as the seekp() and tellp() functions allow you
to set and examine the put pointer.
Chapter 8 31
File Random Access (4/5)
Chapter 8 33
Practical Examples (1/12)
Example 1a: write to a text file
// Create a sequential file.
#include <iostream>
#include <fstream>
using namespace std;
int main(){
ofstream outClientFile( "[Link]", ios::out ); //creating ofstream object
//and opening a file
// check if unable to create file
if ( !outClientFile ) {
cout << "File could not be opened" << endl;
exit( 1 );
} // end if
int account;
char name[ 30 ], ch=‘y’;
double balance;
Chapter 8 34
Practical Examples (2/12)
Example 1a (cont’d)
// read account, name and balance from cin, then place in file
cout << "Enter the account, name, and balance separate by space." << endl;
cout<< "Enter \’N\’ to end input.\n? ";
while (ch == ‘y’)
{
cin >> account >> name >> balance;
outClientFile << account << ' ' << name << ' ' << balance<< endl;
cout << "? ";
cin>>ch;
} // end while
return 0;
} // end main
Chapter 8 35
Practical Examples (3/12)
Example 1b: read from a text file
// Create a sequential file.
#include <iostream>
#include <fstream>
using namespace std;
int main(){
ifstream inClientFile( "[Link]", ios::in); //creating ifstream object and
//opening a file
// check if unable to create file
if ( !inClientFile.is_open() ) {
cout << "File could not be opened" << endl;
exit( 1 );
} // end if
int account;
char name[ 30 ];
double balance;
Chapter 8 36
Practical Examples (4/12)
Example 1b (cont’d)
// read account, name and balance from cin, then place in file
cout << “The User bank account details\n”;
cout<< “Account \t Name\t Balance\n ";
return 0;
} // end main
Chapter 8 37
Practical Examples (5/12)
Example 2: get() and put() functions
#include <iostream>
#include <fstream>
using namespace std;
int main(){
char str[80], c, d, ans;
ofstream outfl("[Link]");
// read a string from keyboard and write to a file.
do{
cout<<"please give the string : ";
gets(str); outfl<<str;
cout <<"do you want to write more...<y/n> : "; ans=getch();
}while(ans=='y');
outfl<<'\0';
[Link]();
Chapter 8 38
Practical Examples (6/12)
Example 2 (cont’d)
// copying file content using get() and put() functions
Ifstream infl("[Link]");
ofstream out("[Link]");
[Link]();
[Link]();
} Chapter 8 39
Practical Examples (7/12)
Example 4a: write to binary file
#include <iostream> void AddRecord(){
#include <fstream> fstream outf;
using namespace std; [Link]("[Link]",ios::app|ios::binary);
struct Student{ getdata();
int roll; [Link]( (char *) &stud, sizeof(stud) );
char name[25]; [Link]();
float marks; }
} stud; int main()
void getdata(){ {
cout<<"\n\nEnter Roll : "; char ch='n';
cin>>[Link]; do{
cout<<"\nEnter Name : "; AddRecord();
cin>>[Link]; cout<<"\nwant to add more (y/n) : ";
cout<<"\nEnter Marks : "; get(ch);
cin>>[Link]; } while(ch=='y' || ch=='Y');
} cout<<"\nData written successfully...";
} Chapter 8 40
Practical Examples (8/12)
Example 4b: read from binary file
#include <iostream> void Display(){
#include <fstream> fstream inf;
using namespace std; [Link]("[Link]",ios::in|ios::binary);
struct Student{
int roll; cout<<"\n\tRoll\tName\tMarks\n";
char name[25];
[Link]( (char *) &stud, sizeof(stud) );
float marks;
while(inf != NULL){
} stud;
putData();
[Link]( (char *) &Stu, sizeof(stud) );
void putData()
}
{
[Link]();
cout<<"\n”<<[Link];
}
cout<<“\t”<<[Link];
cout<<“\t”<<[Link];
int main() {
}
Display ();
}
Chapter 8 41
Practical Examples (9/12)
Example 5: random access void getData(){
/* C++ File Pointers and Random Access cout<<“Student Info:\n”;
* This program demonstrates the concept cout<<"Rollno: "; cin>>[Link];
* of file pointers and random access */ cout<<"Name: "; cin>>[Link];
#include <iostream> cout<<"Marks: "; cin>>[Link];
#include <fstream>
using namespace std; float marks = [Link];
#include <string.h> if(marks>=75) {[Link] = 'A'; }
else if(marks>=60){[Link] = 'B'; }
struct Student{ else if(marks>=50){[Link] = 'C'; }
int roll; else if(marks>=40){[Link] = 'D'; }
char name[25]; else{ [Link] = 'F'; }
float marks; }
char grade;
} stud1, stud; int getrno(){
return [Link];
}
Chapter 8 42
Practical Examples (10/12)
Example 5 (cont’d) cout<<"New name:(Enter '.' to retain z old): ";
void putdata(){
cin>>nam;//seble
cout<<"Rollno: "<<[Link];
cout<<"New marks:(Press -1 to retain z old):";
cout<<"\tName:
cin>>mks;//-1
"<<[Link]<<"\n";
cout<<"Marks: "<<[Link];
if(strcmp(nam, ".")!=0){
cout<<"\tGrade:
strcpy([Link], nam);
"<<[Link]<<"\n";
}
}
if(mks != -1){
void modify(){
[Link] = mks;
cout<<"Rollno:
if([Link]>=75){[Link] = 'A';}
"<<[Link]<<"\n";
else if([Link]>=60){[Link] = 'B';}
cout<<"Name:
else if(marks>=50){[Link] = 'C';}
"<<[Link];//selam
else if([Link]>=40){[Link] = 'D';}
cout<<"\tMarks:
else{ grade = 'F'; }
"<<[Link]<<"\n";//80
}
cout<<"Enter new details.\n";
}
char nam[20]=" "; float mks;
Chapter 8 43
Practical Examples (11/12)
Example 5 (cont’d) cout<<"Enter rollno of student
int main() whose record is to be modified: ";
{ cin>>rno;
fstream fio("[Link]", ios::in | ios::out);
char ans='y‘; [Link](0);
while(ans=='y' || ans=='Y') int size = sizeof(stud1);
{ while(![Link]()){
getdata(); pos = [Link]();//16
[Link]((char *)&stud1, sizeof(stud1)); [Link]((char *)&stud1, size);
cout<<"Record added to the file\n"; if(getrno() == rno){
cout<<"\nWant to enter more ? (y/n).."; modify();
cin>>ans; [Link](pos);
} [Link]((char *)&stud1, size);
found = 't';
//search and modify a record on the file break;
int rno; long pos; char found='f'; }
} }
Chapter 8 44
Practical Examples (12/12)
Example 5 (cont’d)
if(found=='f'){
cout<<"\nRecord not found in the file..!!\n";
cout<<"Press any key to exit...\n";
exit(2);
}
[Link](0);
cout<<"Now the file contains:\n";
while(![Link]())
{
[Link]((char *)&stud, size);
putdata();
}
[Link]();
}
Chapter 8 45
Practical Examples (9/12)
Create a structure called student (ID, Name,
Mark, Grade) –
Create a function called getdata() that accepts
ID, Name and Mark (n elements) from the user.
- Calculate the Grade(pass or fail) from Mark
and Put the data into a file called [Link]
- Create a file for input and print the data
from the student file.
E.G - 5
ID Name Mark Grade
001 Abebe 66 P
002 Helen 55 F
Chapter 8 46
Summary
§ Text Files
§ Standard I/O Streams
§ Binary Files
§ Files streams
File stream Classes
§ Types of file § ifstream
§ ofstream
§ Stream Class Hierarchy
§ fstream
§ File processing steps
§ Creating stream object
§ File read and write functions § Opening a file
§ Check for success of file opening
§ File modes and offsets § Perform read/write operations
§ Closing file
§ File Access Methods
§ File read functions
§ Sequential file access - get(), getline(), read()
§ Random file access § File write functions
- put(), write ()
Chapter 8 47
MCQ
1. What is meant by ofstream in C++ ?
(a) Reads from a file (b) Writes to a file
(c) All of the above (d) None of the Above
2. How many types of output stream classes are there in C++ ?
(a) 2 (b) 3 (c) 1 (d) none
3. Which function is used to position back from the end of file object ?
(a) seekp (b) seekg
(c) tellp (d) tellg
4. Which header file is used for reading and writing to a file ?
(a) #include<file> (b) #include<iostream>
(c) #include<fstream> (d) None of the Above
5. Which one is always faster in writing on C++ ?
(a) Reading from the network (b) Writing to a file
(c) Writing to memory (d) None of the Above
Chapter 8 48
MCQ
6. Which will be used with physical devices to interact from C++ program ?
(a) Streams (b) Programs
(c) Library (d) None of the Above
7. Which header files is required for creating and reading data files ?
(a) console.h (b) ifstream.h
(c) ofstream.h (d) fstream.h
8. What is the benefit of C++ input and output over C input and output ?
(a) Exception (b) Type safety
(c) All of the above (d) None of the Above
9. By default, all the files in C++ are opened in _________ mode.
(a) Text (b) Binary
(c) ASCII d) None
10. Which is the default mode of the opening using the fstream class?
(a) ios::in b) ios::out
(c) ios::in|ios::out (d) ios::trunc
Chapter 8 49
Practical Exercise
1. Write a program that accept N student record from the keyboard & store the
list on a file “D:\\ [Link]” in a text file format. Also write an other program
that reads students record from the text file “D:|\ [Link]” and display on the
screen. (tip: create a header file which contain definition of two function
getRecord() and displayrecord() and include it in your program).
2. Modify your program in Q1 to store the student records a binary file.
3. Write a program which prints a table listing the number of occurrences of the
lower-case characters 'a' to 'z' in a file "[Link]". Declare only one
variable of type "ifstream", one variable of type "char", and two variables of
type "int". The program should produce output such as the following
CHARACTER OCCURRENCES
a 38
b 5
c 35
- -
- -
Chapter 8 50
Practical Exercise
4. Write a function that takes the name of a file (char*) that contains integer
records, an array of int and the address of a variable count. Define the function
to read the file into the array. Assume that the array has enough space to hold
the file. count should be updated to the number of entries in the file.
5. Create a text file containing the following data (without the headings)
Write a C++ program that uses the information in the file created to produce the
following pay report for each employee:
Name Pay Rate Hours Regular Pay Overtime Pay Gross-Pay
Compute regular pay as any hours worked up to and including 40 hours multiplied
by the pay rate. Compute overtime pay as any hours worked above 40 hours times
a pay rate of 1.5 multiplied by the regular rate. The gross pay is the sum of regular
and overtime pay. At the end of the report, the program should display the totals
of the regular, overtime, and gross pay columns
Chapter 8 51
Practical Exercise
6. (Search) A bank’s customer records are to be stored in a file and read into a set
of arrays so that a customer’s record can be accessed randomly by account
number. Create the file by entering five customer records, with each record
consisting of an integer account number (starting with account number 1000), a
first name (maximum of 10 characters), a last name (maximum of 15 characters),
and a double-precision number for the account balance. After the file is created,
write a C++ program that requests a user-input account number and displays the
corresponding name and account balance from the file.
7. Write a C++ program that permits users to enter the following information about
your small company’s 10 employees, sorts the information in ascending ID
number, and then writes the sorted information to a file:
ID No. Sex(M/F) Hourly-Wage Years-with-the-Company
After the records are stored successfully,
(a) write a program that reads the file created one record at a time, asks for the
number of hours each employee worked each month, and calculates and
displays each employee’s total pay for the month
(b) Develop a program that reads the file created and changes the hourly wage or
years for each employee, and creates a new updated file
Chapter 8 52
Reading Resources/Materials
Chapter 14:
✔ P. Deitel , H. Deitel; C++ how to program [10th edition],
Global Edition (2017)
Chapter 14:
✔ Diane Zak; An Introduction to Programming with C++ (8th
Edition), 2016 Cengage Learning
Chapter 6:
✔Walter Savitch; Problem Solving With C++ [10th edition,
University of California, San Diego, 2018
Chapter 18:
✔ Herbert Schildt; C++ From the Ground Up (3rd Edition), 2003
McGraw-Hill, California 94710 U.S.A.
Chapter 8 53
Thank You
For Your Attention!!
Chapter 8 54