0% found this document useful (0 votes)
33 views22 pages

Data File Handling Class XII

Uploaded by

abxrnt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views22 pages

Data File Handling Class XII

Uploaded by

abxrnt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

1

Class XII

Computer Science & Application (CSCA)

Chapter 7 (Data File Handling)

The fstream.h header file

The fstream.h header predefines a set or operations for handling files related to input and output. It
defines certain classes that help to perform file input and output. For example, ifstream class links a file
to the program for input and ofstream class links a file to the program for output and fstream classifies a
file to the program for both input and output. The file operations make use of streams as an interface
between the programs and the files, A stream is a sequence of bytes and general name given to flow of
data. Input stream and output stream represent different kind of data flow into the memory or out of
the memory. The C++ provides ofstream class to write on files, ifstream class to read from files and
fstream class to both read and write from/to file. These classes are derived from fstreambase and from
those declared in the header file ” iostream.h”. The classes ofstream, ifstream, and fstream are designed
exclusively to manage the disk files and their declaration are present in the header file “fstream.h”. To
make use of these classes, fstream.h is included in all the programs which handle disk files.

Data File

The darta files can be stored in two ways:

 Text File
 Binary Files

Difference between text file and binary file

Text File Binary File


1 The text files can easily be transferred from one Binary files cannot easily be
computer system to another. transferred from one computer system
to another due to variations in the
internal variations in the internal
representation which varies from
computer to computer.
2 It stores data using ASCII format i.e. human- It stores data in binary format i.e. with
readable graphic characters. the help of 0 and 1.
3 These files are easily readable and modifiable These files are not easily readable and
because the content written in text files is human modifiable because the content
readable. written in binary files is not human-
Content written in binary files is not human- readable and it is encrypted content.
readable and looks like encrypted content.
4 These files create portability problems. These files are easily portable.
5 Text files save the data by converting each digit in These save memory because the data
data into ASCII format which will take up much of of any type will get stored in memory
the space as compared to the required one. as per its memory size.
6 Any file is by default text file. The ios:: binary mode has to be used
with binary files while opening them.
7 Error in a textual file can be easily recognized and Error in a binary file corrupts the file
2

eliminated. and is not easily detected.

Opening and Closing Files

The C++ language provides a mechanism to store the output of a program in a file and browse from a
file on the disk. This mechanism is termed file handling. In order to perform file handling, some
general functions which are used are as follows:
 open(): This function helps to create a file and open the file in different modes, like input
operations, output operations, binary mode, etc.
 close(): This function helps to close an existing file.
 get(): This function helps to read a single character from the file.
 put(): This function helps to write a single character in the file.
 read(): This function helps to read data from a file.
 write(): This function helps us to write data into a file.

A stream is an abstraction that represents a tool on which operations of input and output are
performed. A stream is often represented as a source or destination of characters of indefinite length,
counting on its usage. So far, the header file which provides functions cin and cout is used to require
input from the console and write output to a console respectively. In C++ there is a group of file
handling methods. These include ifstream, ofstream, and fstream . These classes are obtained
from fstreambase and from the corresponding iostream class. These classes are designed such that
they are able to manage the disk files, declared in fstream, and thus this file must be included in any
program that uses files.

fstream Library: Fstream is a library that consists of both, ofstream and ifstream which means it can
create files, write information to files, and read information from files. This header file is generally
used as a data type that represents the file stream. Which is used while describing the syntax to open,
read, take input and close the file, etc.
How To Close File? In order to use a disk file for storing data, the following parameters need to be
decided about the file and its intended use. The parameters that are to be noted are as follows:

 A name for the file.


 Data type and structure of the file.
 Purpose (reading, writing data).
 Opening method.
 Closing the file after use.
This article focuses on closing the file. In a case, if a C++ program terminates, then it automatically
flushes out all the streams, releases all the allocated memory, and closes all the opened files.
Therefore, it is a good alternative to use the close() function to close the file-related streams, and it is
a member of ifsream, ofstream, and fstream objects.
Syntax:
close()
Properties:
 Return value: The close() function provides no return value which means that if the operation
fails, including if no file was open before the call, the failbit state flag is set for the stream (which
may throw ios_base::failure if that state flag was registered using member exceptions.
3

 Exception handling: When the function is provided with an exception and the stream is in a valid
state, then any exception thrown by an internal operation is caught by the function and rethrown
after closing the file. It throws an exception to member type failure only if the function fails
(setting the failbit state flag) and member exceptions are set to throw for that state.
 It modifies the fstream object. Concurrent access to an equivalent stream may introduce data
races.

Opening Files using Open() Function

Check Textbook

The Concept of File Mode

So far, we have been using the iostream standard library, which provides cin and cout methods for
reading from standard input and writing to standard output respectively.
This tutorial will teach you how to read and write from a file. This requires another standard C++ library
called fstream, which defines three new data types −

Sr.N Data Type & Description


o

1
ofstream
This data type represents the output file stream and is used to create files and to write
information to files.

2
ifstream
This data type represents the input file stream and is used to read information from files.

3
fstream
This data type represents the file stream generally, and has the capabilities of both ofstream
and ifstream which means it can create files, write information to files, and read information
from files.

To perform file processing in C++, header files <iostream> and <fstream> must be included in your C++
source file.

Opening a File

A file must be opened before you can read from it or write to it. Either ofstream or fstream object may
be used to open a file for writing. And ifstream object is used to open a file for reading purpose only.
4

Following is the standard syntax for open() function, which is a member of fstream, ifstream, and
ofstream objects.
void open(const char *filename, ios::openmode mode);
Here, the first argument specifies the name and location of the file to be opened and the second
argument of the open() member function defines the mode in which the file should be opened.

Sr.No Mode Flag & Description

1
ios::app
Append mode. All output to that file to be appended to the end.

2
ios::ate
Open a file for output and move the read/write control to the end of the file.

3
ios::in
Open a file for reading.

4
ios::out
Open a file for writing.

5
ios::trunc
If the file already exists, its contents will be truncated before opening the file.

You can combine two or more of these values by ORing them together. For example if you want to open
a file in write mode and want to truncate it in case that already exists, following will be the syntax −
ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc );
Similar way, you can open a file for reading and writing purpose as follows −
fstream afile;
afile.open("file.dat", ios::out | ios::in );

Closing a File

When a C++ program terminates it automatically flushes all the streams, release all the allocated
memory and close all the opened files. But it is always a good practice that a programmer should close
all the opened files before program termination.
5

Following is the standard syntax for close() function, which is a member of fstream, ifstream, and
ofstream objects.
void close();

Steps to Process a file in your Program

Before you actually start using and manipulating files in your C++ programs, let's discuss the steps you
need to follow in order to use files in your C++ program.

Here are the steps listed that need to be followed in the order to process a file in a C++ program. The
five steps to use files in your C++ program are:

1. Determine the type of link required.


2. Declare a stream for the desired type of link.
3. Attach the desired file to the stream.
4. Now process as required.
5. Close the file-link with stream.

Let's discuss these steps in details now. To facilitate your understanding, I'll be using an example for it.
For instance, if you have to write a program for the following:

Get rollnumber and marks of the students of a class (get these details from user) and store these details
into a file called marks.dat.

Let's now discuss the above mentioned five steps with the help of above example. But before this, shall I
tell you an interesting thing - you've been working with file streams right from the day one of C++
programming. This is because, (I/O) devices are implemented as files in C++. This cin and cout are
actually the streams that you use for input and output. The cin, the input stream, is linked to keyboard
and cout, the output stream is linked to monitor.

Step 1 - Determine the type of link required

First step requires the identification of type of link required. If the data is to be brought in from a file to
memory, the the link can be said to be File-to-Memory link. Similarly, if the data (after some processing)
is to be sent from memory to file, then the link can be said to be Memory-to-File link. And if a situation
demands both types of links, then two-way (File-to-Memory and Memory-to-File) link can be created.

Predefined stream cin is an example of File-to-Memory link. Since devices are treated as files, keyboard
is also treated as file. With cin, data comes from the file i.e., keyboard to Memory and hence file-to-
memory link and with cout, data goes from memory to file i.e., monitor, hence Memory-to-File link. We
can summarize those link as follows :

Link Used for


6

File-to-Memory
(IN TO the Input purposes i.e., to bring data from file to memory for further processing.
Memory)

Memory-to-File
(OUT FROM the Output purposes i.e., to send processed data from memory to the file.
Memory)

File-to-Memory/
Input/Output purposes.
Memory-to-File

Example Processing : Step 1

In the example-problem given above, it is given that data is to be read from the user i.e., through the
keyboard (file) the data should be brought in memory (for which cin is already declared) and then these
read details are to be stored in a file i.e., from memory, data should be sent in the file called marks.dat.

For the reading purpose, file-to-memory link is required for keyboard but for this cin is already declared
and to store this data in file, the memory-to-file link is required. Since for marks.dat, no predefined link
is available, we'll have to create this type of link.

Thus, we have determined the type of link required for file marks.dat, which is Memory-to-File type link.

Step 2 - Declare a stream for the desired type of link

After determining the type of link required, the next step is to create a stream for it. In order to create
file streams, the header file fstream.h is included in the program and if you have included fstream.h then
you need not include iostream.h as cin, cout declarations are also available in fstream.h.

For different types of links, different streams classes are used for stream declarations. For File-to-
Memory (i.e., input) type of link, ifstream class-type's stream is declared. For example,

ifstream fin; //stream name here is fin

You can choose any name (meeting the identifier naming rules and conventions) for the stream being
declared). For Memory-to-File (i.e., output) type of link, ofstream class-type's stream is declared. And for
File-to-Memory/Memory-to-File (i.e., I/O) type of link, fstream class-type's stream is declared. For
example,

ofstream fout; //stream name here is fout.


fstream fio ; //stream name here is fio.
Type of Link Stream Class Example Declaration
7

File-to-Memory (IN TO the Memory) ifstream ifstream fin ;

Memory-to-File (OUT FROM the Memory) ofstream ofstream fout ;

File-to-Memory/Memory-to-File fstream fstream fio ;

Following table summarizes these stream types as :

Example Processing : Step 2

For the above mentioned example, we have already determined the link type to be Memory-to-File for
file marks.dat. In order to declare a stream for it, we may write as follows :

ofstream fout ; //stream name here is fout

Step 3 - Attach the desired file to the declared stream

After declaring streams, the next step is to link the file with the declared stream. This is done by opening
the desired file.

For example, if a file named sample.dat is to be opened in input mode i.e., linked to a stream of ifstream
type, we can do it in the following two ways :

1st Way:

ifstream fin("Sample.dat", ios::in) ; //using constructor

2nd Way:

fin open("Sample.dat", ios::in) ; //using open()

Notice that in the above examples, a file mode (ios::in here) is used. ios::in is the default file mode for
ifstream type of stream.

Similarly, in order to open a file, say oput.txt, in output mode i.e., to link it with a stream of ofstream
type, we may write :

ofstream fout("oput.txt", ios::out) ; //using constructor

Or as ofstream fout :

fout.open("oput.txt", ios::out) ; //using open()

To open a file, say newfile.txt, in I/O mode (stream of fstream) type, we may write as
8

fstream fio("newfile.txt", ios::in | ios::out) ; //using constructor

Or as fstream fio:

fio.open("newfile.txt", ios::in | ios::out) ; //using open

Notice that, multiple file modes are separated by a bitwise or (|) pipe sign.

Example Processing : Step 3

Now, with all the information/knowledge gained so fat, let us apply this on our example problem given
above.

We may either combine step 2 and step 3 as follows :

ofstream fout("marks.dat", ios::out) ;

Or we may write then separately as :

ofstream fout ;
fout.open("marks.dat", ios::out) ;

Step 4 - Process as required

Under this step, whatever processing is required for the given problem, is performed for instance, our
given example-problem requires us to read marks and rollno's of students of a class and store them into
file called marks.dat.

Example Processing : Step 4

For this, we already have declared the stream and linked our file marks.dat with it. Now its time for
processing. The code fragment for processing is given below :

:
char ans = 'y' ;
int rollno ;
float marks ;

while(ans == 'y' || ans == 'Y')


{
cout << "\nEnter roll number : " ;
cin >> rollno ;
cout << "\nEnter marks : " ;
cin >> marks ;

/* now student's rollno and marks have been read these details are to be
* put into the file's buffer, in order to store them on to the file
9

*/

fout << rollno << '\n' << marks << '\n' ;

/* Notice that the way we send details to output buffer cout, same way we have
* sent those details to output buffer fout. Also, notice that we have also
* sent new line ('\n') after every piece of data. It is done to separate various
* data items.
*/

cout << "\nWant to enter more ? (y/n) " ;


cin >> ans ;

} //end of while

Step 5 - Close the file link with stream

This is the final step where we de-link the file with stream. This is performed through close() function.
For example, if the file-stream is fin, then we need to write as :

fin.close();

Similarly, if the stream-name is fio, we'll write it as :

fio.close();

Notice that to de-link a file, there is no need to mention file name, only stream-name (to which the file is
linked) is required.

Example Processing : Step 5

To de-link our file marks.dat with the stream fout, we need to write :

fout.close() ;

The Complete Example Program

If we put together all the pieces of codes used for our example-problem, the program will look like the
one given below :

Get rollnumbers and marks of the students of a class (get from the user) and store these details into a
file called marks.dat :

/* C++ Steps to Process a File in a Program


* This program demonstrates, how to process
* a file in a C++ program */

#include<conio.h>
10

#include<fstream.h>
void main()
{
clrscr();
ofstream fout; // stream decided and declared - step 1 & 2
fout.open("marks.dat", ios::out); // file linked - step 3
char ans = 'y' ; // process as required - step 4 begins
int rollno;
float marks ;
while(ans == 'y' || ans == 'Y')
{
cout << "\nEnter Rollno. : " ;
cin >> rollno ;
cout << "\nEnter Marks : " ;
cin >> marks ;
fout << rollno << '\n' << marks << '\n' ;
cout << "\nWant to enter more ? (y/n) " ;
cin >> ans ;
}

fout.close() ; // de-link the file - step 5


getch();
}

Here is the sample run of the above C++ program:

Sequential I/O with Files


11

The file stream classes support a number of member functions for performing the input and output
operations on files. The functions get() and put() are capable of handling a single character at a time. The
function getline() lets you handle multiple characters at a time. Another pair of functions i.e., read() and
write() are capable of reading and writing blocks of binary data.

The get(), getline() and put() Functions

The functions get() and put() are byte-oriented. That is, get() will read a byte of data and put() will write
a byte of data. The get() has many forms, but the most commonly used version is shown here, along
with put() :

istream & get(char & ch) ;


ostream & put(char ch) ;

The get() function reads a single character from the associated stream and puts that value in ch. It
returns a reference to the stream. The put() writes the value of ch to the stream and returns a reference
to the stream.

The following program displays the contents of a file on the screen. It uses the get() function :

/* C++ Sequential Input/Output Operations on Files */

#include<iostream.h>
#include<stdlib.h>
#include<fstream.h>
#include<conio.h>
void main()
{
char fname[20], ch;
ifstream fin; // create an input stream
clrscr();

cout<<"Enter the name of the file: ";


cin.get(fname, 20);
cin.get(ch);

fin.open(fname, ios::in); // open file


if(!fin) // if fin stores zero i.e., false value
{
cout<<"Error occurred in opening the file..!!\n";
cout<<"Press any key to exit...\n";
getch();
exit(1);
}

while(fin) // fin will be 0 when eof is reached


{
12

fin.get(ch); // read a character


cout<<ch; // display the character
}

cout<<"\nPress any key to exit...\n";


fin.close();
getch();
}

Here is the sample output of the above C++ program. Let's suppose that the file contain the following
information:

As stated, when the end-of-file is reached, the stream associated with the file becomes zero. Therefore,
when fin reaches the end of the file, it will be zero causing the while loop to stop.

The next program uses the put() function to write all characters with ASCII values 33 to 127 to a file
called Aschars:

/* C++ Sequential Input/Output Operations with Files */

#include<iostream.h>
#include<fstream.h>
#include<stdlib.h>
#include<conio.h>
void main()
{
ofstream fout; // create output stream
char ch;
int line=0;
int i;
clrscr();

fout.open("Aschars", ios::app) ;
if(!fout) // if fout is zero
13

{
cout<<"The file cannot be opened..!!\n";
cout<<"Press a key to exit...\n";
getch();
exit(1);
}
/* write the characters */
for(i=33; i<128; i++)
{
fout.put((char)(i));
}

fout.close();
/* now display the contents of the file */

ifstream fin;
fin.open("Aschars", ios::in);

fin.seekg(0);
for(i=33; i<128; i++)
{
fin.get(ch); // read a character
cout<<i<<" = "; // display the character
cout.put((char)(i));
cout<<"\t";
if(!(i%8))
{
cout<<"\n";
line++;
}
if(line>22)
{
system("PAUSE");
line = 0;
}
}

cout<<"\n\nPress a key to exit..\n";


getch();
}

Here is the sample output of the above C++ program:


14

The Other Forms of get() Function

In addition to the form shown earlier, there are several other forms of get() function. Two most
commonly used form shave the following prototypes :

istream & get(char ∗ buf, int num, char delim = '\n') ; // #1


int get() ; // #2

The first form (#1) reads characters into a character array pointed to bye buf until either num characters
have been read, or the character specified by delim has been encountered. For example, the following
statements :

char line[40] ;
cin.get(line, 40, '$') ;

will read characters into line until either 40 characters are read or '$' character is encountered,
whichever occurs earlier. That is, if the input given in response to above statement is as follows :

Value is $ 177.5

then line will be storing

value is

And if the input given is as follows :

The amount is 17.5

The contents of line will be

The amount is 17.5.


15

The array pointed to by buf (any user defined name) will be null-terminated by get(). If no delim
character is specified, by default a newline character acts as a delimiter. If the delimiter character is
encountered in the input stream the get() function does not extract it. Rather, the delimiter character
remains in the stream until the next input operation.

The second form (#2) of get() returns the next character form the stream. It returns EOF if the end of the
file is encountered. For example, the following code fragment illustrates it :

int i;
char ch;
ch = i = fin.get() ;

If the input given is A, then the value of i will be 65 (ASCII value of A) and the value of ch will be 'A'.

The getline() Function

Another member function that performs input is getline() whose prototype is :

istream & getline(char * buf, int num, char delim = '\n') ;

As you can see, this function in virtually identical to get(buf, num, delim) version of get(). The function
getline() also reads characters from input stream and puts them in the array pointed to by buf until
either num character have been read, or the character specified by delim is encountered. If not
mentioned, the default value of delim is newline character.

The read() and write() Functions

Another way of reading and writing blocks of binary data is to use C++'s read() and write() functions.
Their prototypes are :

istream & read( (char *) & buf, int sizeof(buf) ) ;


ostream & write( (char *) & buf, int sizeof(buf) ) ;

The read() function reads sizeof(buf) (it can be any other integer value also) bytes from the associated
stream and puts them in the buffer pointed to by buf. The write() function writes sizeof(buf) (it can be
any other integer value also) bytes to the associated stream from the buffer pointed to by buf.

As you see, these functions take two arguments. The first is the address of variable buf, and the second
is the length of that variable in bytes. The address of the variable must be type cast to type char * (i.e., a
pointer to character type).

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

The following program writes a structure to the disk and then reads it back in using write() and read()
functions :

/* C++ Sequential Input and Output Operations with Files */


16

#include<iostream.h>
#include<fstream.h>
#include<string.h>
#include<stdlib.h>
#include<conio.h>

struct customer
{
char name[20];
float balance;
};

void main()
{
clrscr();
customer savac;
cout<<"Enter your name: ";
cin.get(savac.name, 20);
cout<<"Enter balance: ";
cin>>savac.balance;

ofstream fout;
fout.open("Saving", ios::out | ios::binary); // open output file
if(!fout)
{
cout<<"File can\'t be opened..!!\n";
cout<<"Press any key to exit...\n";
getch();
exit(1);
}

fout.write((char *) & savac, sizeof(customer)); // write to file


fout.close(); // close connection

// read it back now


ifstream fin;
fin.open("Saving", ios::in | ios::binary); // open input file
fin.read((char *) & savac, sizeof(customer)); // read structure
cout<<savac.name; // display structure now
cout<<" has the balance amount of Rs. "<<savac.balance<<"\n";
fin.close();

cout<<"\nPress a key to exit...\n";


getch();
}

Here is the sample run of the above C++ program:


17

As you can see, only a single call to read() and write() is necessary to read or write the entire structure.
Each individual field need not be read or written separately.

If the end of the file is reached before the specified number of characters have been read, the read()
simply stops, and the buffer contains as many characters as were available.

Reading and Writing Class Objects

The functions read() and write() can also be used for reading and writing class objects. These functions
handle the entire structure of an object as a single unit, using the computer's internal representation of
data. For example, the function write() copies a class object from memory byte by byte with no
conversion. But one thing that must be remembered is that only data members are written to the disk
file and not the member functions.

The length of an object is obtained by sizeof operator and it represents the sum total of lengths of all
data members of the object. Here is an example:

/* C++ Sequential Input and Output Operations with Files */

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

class student
{
char name[20];
char grade;
float marks;

public:
void getdata(void);
void display(void);

};
18

void student::getdata(void)
{
char ch;
cin.get(ch);
cout<<"Enter name: ";
cin.getline(name, 20);
cout<<"Enter grade: ";
cin>>grade;
cout<<"Enter marks: ";
cin>>marks;
cout<<"\n";
}

void student::display(void)
{
cout<<"Name: "<<name<<"\tGrade: "<<grade<<"\tMarks: "<<marks<<"\n";
}

void main()
{
clrscr();
char fname[20];
student cse[3]; // declare array of 3 objects
fstream fio; // input and output file

cout<<"Enter file name: ";


cin.get(fname, 20);

fio.open(fname, ios::in || ios::out);


if(!fio)
{
cout<<"Error occurred in opening the file..!!\n";
cout<<"Press any key to exit...\n";
getch();
exit(1);
}

cout<<"Enter details for 3 students:\n\n";


for(int i=0; i<3; i++)
{
cse[i].getdata();
fio.write((char *)&cse[i], sizeof(cse[i]));
}

fio.seekg(0); /* seekg(0) resets the file to start, to access the file


* from the beginning */
cout<<"The content of "<<fname<<" file are shown below:\n";
19

for(i=0; i<3; i++)


{
fio.read((char *)&cse[i], sizeof(cse[i]));
cse[i].display();
}

fio.close();

cout<<"\nPress any key to exit...\n";

getch();
}

Here is the sample run of the above C++ program:

Detecting EOF

The eof() method of ios class in C++ is used to check if the stream is has raised any EOF (End Of File)
error. It means that this function will check if this stream has its eofbit set.
Syntax:
bool eof() const;
Parameters: This method does not accept any parameter.
Return Value: This method returns true if the stream has eofbit set, else false.
20

/ C++ code to demonstrate

// the working of eof() function

#include <bits/stdc++.h>

using namespace std;

int main()

// Stream

stringstream ss;

// Using eof() function

bool isEOF = ss.eof();

// print result

cout << "is stream eof: "

<< isEOF << endl;


21

return 0;

Output:
is stream eof: 0
Example 2:

// C++ code to demonstrate

// the working of eof() function

#include <bits/stdc++.h>

using namespace std;

int main()

// Stream

stringstream ss;

ss.clear(ss.eofbit);
22

// Using eof() function

bool isEOF = ss.eof();

// print result

cout << "is stream eof: "

<< isEOF << endl;

return 0;

Output:
is stream eof: 1

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy