File Handling in C++

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 23

Lecture 14

File Handling in C++


Contents
 Objectives
 File definition
 Files & Streams
 Modes
 File types
 Examples
Objective
 Variables: simple or structures
 Store data temporarily
 Storage is scope dependent
 What if we need to store data permanently
 We need to store data of variables in some permanent
place.
 At some storage device like application program
 We need to give name to stored data for future access
 Access can be for read or write
What is a File?

 A file is a collection of related data that a computers treats


as a single unit.
 Storage of data in memory is temporary. Files are used for
data persistence, i.e., permanent retention of data.
 Computers store files to secondary storage devices, like
hard disks, CDs, DVDs, flash drives and tapes, so that the
contents of files remain intact when a computer shuts
down.
 When a computer reads a file, it copies the file from the
storage device to memory; when it writes to a file, it
transfers data from memory to the storage device.
 A buffer is a “special work area” that holds data as the
computer transfers them to/from memory.
 Buffers help to synchronize data.
Files & Streams
 C++ views each file simply as a sequence of bytes. Each file ends
either with an end-of-file marker or at a specific byte number
recorded in an operating-system-maintained administrative data
structure.

 When a file is opened, an object is created, and a stream is


associated with the object.
 cin object is created when <iostream> is included.
 To perform file processing in C++, headers <iostream> and
<fstream> must be included.
 Header <fstream> includes the definitions for the stream class
templates
 basic_ifstream—a subclass of basic_ istream for file input
 basic_ofstream —a subclass of basic_ostream for file output
 basic_fstream —a subclass of basic _ iostream for file input and output.
Files & Streams
 ifstream is an alias for basic_ifstream
 ofstream is an alias for basic_ofstream
 fstream is an alias for basic_fstream

 In this lecture, we consider programs that create, update and process


data files.
 Files can be sequential or random-access data files.
 Sequential file:
 Program on next slide creates a sequential file that is used in an accounts-
receivable system to help manage the money returned to a company by its
credit clients in return of services received in the past.
 The data obtained for each client constitutes a record for that client.
 This program assumes the user enters the records in account-number order.
Files & Streams

 Output:
Open a File
 Previous program writes data to a file, so we open the file for output (or for
writing) by creating an ofstream object.
 Two arguments are passed to the object’s constructor (line 11)—the filename and
the file-open mode.
 Main purpose of the constructor in C++ is to construct an object of the class. In
other words, it is used to initialize all class data members.
 Its like a member function of a class.
 For an ofstream object, the file-open mode can be either ios::out (the default) to
output data to a file or ios::app to append data to the end of a file.
 We create an ofstream object named outClientFile associated with the file
clients.txt that’s opened for output.
 because we did not specify a path to the file (that is, it’s location), the file will be in
the same directory as the program.
 The ofstream opens the file— this establishes a “line of communication” with the
file.
 Since ios:: out is the default argument, so we can write the statement as:
ofstream outClientFile{"clients.txt"};
 If the specified file does not yet exist, then the ofstream object creates the file,
using that filename.
File-open Modes
• Since ios::out write to the file, so there are chances of data loss
in the file. Create a backup of file before opening it this mode.
Opening a File via the open
 You can create an ofstream object without opening a specific file, i.e.,
a file can be attached to the object later.
 ofstream outClientFile;
creates an ofstream object that’s not yet associated with a file. The
ofstream member function open opens a file and attaches it to an
existing ofstream object as
 outClientFile. open("clients.txt",ios::out);
 Check whether the open operation is successful (see the lines 14-17 in
the previous program). Reasons for failure could be :
 attempting to open a nonexistent file for reading
 attempting to open a file for reading or writing from a directory that you don’t
have permission to access, and
 opening a file for writing when no disk space is available.
Processing Data
 If file opens successfully, the program begins processing data. program
prompts the user to enter either the various fields for each record or the end-
of-file indicator when data entry is complete.

 The user enters end-of-file to inform the program to process no additional


data.
Close a File
 Once the user enters the end-of-file indicator, main terminates. This
implicitly invokes outClientFile’s destructor, which closes the clients.txt
file.
 You can also close the ofstream object explicitly, using member function
close as follows:
 outClientFile.close( );
 Note: Always close a file as soon as it’s no longer needed in a program to
prevent any error.
Reading Data from a Sequential File
 Files store data so it may be retrieved for processing when needed.
 Creating an ifstream object opens a file for input (or read). The ifstream
constructor can receive the filename and the file-open mode as arguments
and establishes a “line of communication” with the file.
 If a file’s contents should not be modified, use ios::in to open it only for input.
 Objects of class ifstream are opened for input by default, so the statement
ifstream inClientFile("clients.txt" ) ;
opens clients.txt for input.
 Program on the next slide opens the file for input or reading purpose.
Example to Read a File

Output
read(), write(), put() and get() functions
 read(): reads a block of code from a file.
 write(): writes a block f code into the file.
 put(): puts a single character in a file.
 get(): reads a single character from a file.
Random-Access Files
 Sequential files are inappropriate for instant-access applications, in
which a particular record must be located immediately.
 Common instant-access applications are airline reservation
systems, banking systems, point-of-sale systems that require rapid
access to specific data.
 Individual records of a random-access file can be accessed directly
(and quickly) without having to search other records.
 Data can be inserted into a random-access file without destroying
other data in the file. Data stored previously also can be updated or
deleted without rewriting the entire file.
Creating a Random-Access Files
 The ostream member function write() outputs to the specified
stream a fixed number of bytes, beginning at a specific location in
memory.
 When the stream is associated with a file, function write() writes
the data at the location in the file specified by the put file-position
pointer.
 The istream member function read() inputs a fixed number of
bytes from the specified stream to an area in memory beginning at
a specified address. If the stream is associated with a file, function
read() inputs bytes at the location in the file specified by the “get”
file-position pointer.
File-Position Pointers
 Programs normally read sequentially from the beginning of a file and
read all the data consecutively until the desired data is found.
 Once you have a file open, you can navigate to different parts of the
file. This is often referred to as random access of files.
 We can change the read and write position of the file.
 istream and ostream provide member functions— seekg(“seek get”)
and seekp(“seek put”), respectively—to reposition the file-position
pointer.
 Each istream (ostream) object has a get (put) pointer, which indicates
the byte number in the file from which the next input (output) is to
occur.
 The statement, inClientFile.seekg(0); , repositions the file-position
pointer to the beginning of the file (location 0).
File-Position Pointers
 A second argument can be specified to indicate the seek direction, which can
be ios::beg (the default) for positioning relative to the beginning of a stream.

 seekg(50, ios::beg); will set the put pointer to 50 bytes from the begining of
the file and start reading the data.
 seekg(50, ios::cur); will set the put pointer to 50 bytes from the current
location of the file.
 seekg(-50, ios::end); will set the put pointer to 50 bytes before the end of the
file.
 Same arguments are used in seekp() for writing the data in the file.
Detecting End-of-File
 When we read a file, as we do here, we will eventually
encounter an end-of-file (EOF) condition. The EOF is a
signal sent to the program from the operating system when
there is no more data to read.
int main()
{
const int MAX = 80; //size of buffer
char buffer[MAX]; //character buffer
ifstream infile(“TEST.TXT”); //create file for input
while( !infile.eof() ) //until end-of-file
{
infile.getline(buffer, MAX); //read a line of text
cout << buffer << endl; //display it
}
return 0;
}
Example: seekp()& seekg()
 Write the following text in brain.txt file and save it.
 Hello|Hello
 Hi|Hello
 Who are you|I am a new employee
 whats up|Hello

1.#include <fstream> int main() {


2.#include <iostream>  //input file stream
3.#include <cstring>  ifstream infile;
using namespace std;  //open the file
 infile.open("F:\\brain.txt");
 //close your file!
 infile.close();
 return 0;
}
seekg()
1.string searchResult;
2.infile.seekg(10);
3.getline(infile, searchResult);
4.cout << "10 from Beginning = " << searchResult << endl;
5.infile.seekg(5, ios::cur);
6.getline(infile, searchResult);
7.cout << "5 from Current = " << searchResult << endl;
8.infile.seekg(-10, ios::end);
9.getline(infile, searchResult);
10.cout << "-10 from End = " << searchResult << endl;

Output:
10 from Beginning = llo
5 from Current= Hello
-10 from End = up|Hello
seekp()
//output file stream
ofstream outfile;
//open the file
//use ios::in and ios::out to ensure seekp does not replace all text
outfile.open("F:\\brain.txt", ios::in|ios::out);
string insertText = "I can't do that, Hal";
outfile.seekp(12, ios::beg);
outfile << insertText << endl;

Output:

It will insert the above string in the brain.txt file.

You might also like