0% found this document useful (0 votes)
15 views10 pages

FILE HANDLING v2

File handling

Uploaded by

Mahima
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)
15 views10 pages

FILE HANDLING v2

File handling

Uploaded by

Mahima
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/ 10

FILE HANDLING

FILE:
1. A file is a collection of related data stored in a particular area on the disk.
2. A program involves either or both of the following kinds of data communication-
� Data transfer between console unit and the program.
� Data transfer between the program and a disk file.
3. The Input Stream extracts or reads data from the file and the Output Stream
inserts or writes data to the file.

FILE STREAM CLASSES


These include ifstream, ofstream, fstream, derives from the fstreambase class.

OPENING AND CLOSING A FILE


If we want to use a disk file, we need to see the following things:
1. Suitable name for the file.
2. Data type and structure.
3. purpose
4. opening method

�A file can be opened in the following ways:


1. Using the constructor function of the class.
2. Using the member function open() of the class.

Opening files using the constructor function of the class


1. A constructor is used to initialize an object while it is being created.
2. Filename can be used to initialize the file stream object.

STEPS INVOLVED:

Create a file stream object to manage the stream using the appropriate class. i.e.
Ofstream is used to create the output stream and the class Ifstream is used to create
the input stream.

1. Initialize the file object with the desired filename.

E.g.–1) <classname><objectname>;

student obj1;

ofstream outfile(“results”);

Here ofstream is the file stream class and outfile is the object of the class ofstream.
The above statement will open the file named “results” for the output.

2) Similarly, ifstream file class can be used to open an input file.

Ifstream infile(“data”);

The above statement will open the file named “data” as an input file.

A SIMPLE PROGRAM TO WRITE IN A FILE AND READ FROM


THE FILE
#include<iostream.h>
#include<fstream.h>
#include<conio.h>

void main()
{
ofstream outf("student"); //creating the file named "student" using ofstream class

int roll_no;
char name[30];

cout<<"Enter roll no:"; //getting roll no from the user


cin>>roll_no;
cout<<"Enter name:";
cin>>name;

outf<<roll_no<<"\n"; //write to the file "student"


outf<<name<<"\n";

outf.close(); // closing the filestream object outf

ifstream inf("student"); //opening the "student" file in the input mode using ifstream
class

inf>>roll_no; // reading from the file using ifstream object


inf>>name;

cout<<"roll no is "<<roll_no<<"\n"; //displaying to the screen from the file


“student"
cout<<"name is "<<name<<"\n";

inf.close(); // closing the fstream object inf

getch();

Opening files using the member function open() of the class


1. The function open() can be used to open multiple files that use the same stream
object.
2. Syntax for opening the file is as follows:
File_stream_class stream_object;
Stream_object.open(“filename”);

Eg- fstream outf;

outf.open(“student”);

A PROGRAM TO READ AND WRITE TO THE FILE USING OPEN( )

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

void main()
{
ofstream fout; //creating an object fout for the output stream ofstream class

fout.open("student"); //open the file "student" using fout object

fout<<"i am a bca student \n"; //write to the file "student"


fout<<"i study c++ \n";
fout<<"i am in 3rd sem \n";

fout.close(); //closing the file "student"

fout.open("teacher"); //opening the file "teacher" using fout object

fout<<"i am teaching c++ \n"; //write to the file "teacher"


fout<<"my name is charan \n";

fout.close(); //closing the file "teacher"

char buffer[100]; //declaring a buffer of size 100 to store data read from the file

ifstream fin; //creating the input stream object

fin.open("student"); //opening the "student" file in the input or read mode


while(fin) //checks end of file(the condition is true till the end of file comes)
{
fin.getline(buffer,100); //reads 100 characters of a line from the file into the
buffer
cout<<"\n";
cout<<buffer; //display the contents from buffer to the screen
}
fin.close(); //closing the file object "student"

fin.open("teacher"); //opening the file "teacher" in the read mode


while(fin)
{
fin.getline(buffer,100);
cout<<"\n";
cout<<buffer;
}
fin.close(); //closing the file "teacher"

getch();
}

DETECTING THE END OF THE FILE

1. Detection of the end of the file is necessary for preventing any further
attempt to read data from the file.
Example:-
while( fstream object)
while(fin)

Here, fin is the ifstream object. It returns 0 if any error occurs in the file
operation including end of file condition. Hence, the while loop will terminate
when fin will return a 0 on reaching the end of file condition.

2. There is another way to detect the end of file condition. It can be done by the
following statement:-
if (fin.eof( ) != 0)
{
exit(1);
}

Here, eof( ) is a member function of the class ios. It will return a non-zero
value if the end-of-file (EOF) condition is encountered and a zero otherwise.
Hence, the above statement will terminate the program on reaching the end
of the file.

FILE MODES
1. The function open( ) can also take 2 arguments, the first argument is the
“filename” and the second argument is used for specifying the file mode.

The syntax for the function open( ) is:-


stream object.open(“filename”, mode);

Here, the 2nd argument specifies the purpose for which the file is opened.

2. If the 2nd argument is not specified then how the file is opened. In this
case, it will take default values:
ios::in for ifstream functions i.e. open for reading only
ios::out for ofstream functions i.e. for writing only

Parameter Meaning

Ios::app Append to end of file

Ios::ate Go to end of file on opening

Ios::binary Binary file

Ios::in Open file for reading only

Ios::out Open file for writing only

Ios::nocreate Open fails if the file does not exist

Ios::noreplace Open fails if file already exists

Ios:trunk Delete contents of file if it exists

FILE POINTERS

⮚ The file stream classes support the following function:-


1. seekg( ) : moves get pointer to a specified location.
2. seekp( ) : moves put pointer to a specified location.
3. tellg( ) : gives the current position of the get pointer.
4. tellp( ) : gives the current position of the put pointer.

Example:-
ofstream outf;
outf.open(“abc”, ios::app);
int p = outf.tellp( );

Here, the above statements will move the output pointer put to the end of the file
named “abc” and the value of p will represent the total number of bytes in the file
as tellp( ) will return the current position of the pointer and currently the pointer
is at the end of the file.

⮚ “Seek” functions like seekg( ) and seekp( ) can also be used with two
arguments as follows:-
seekg(offset, refposition);
seekp(offset, refposition);

The parameter “offset” represents the number of bytes the file pointer is to be
moved from the location specified by the parameter refposition.
The refposition can take one of the following constants defined in the ios class:-
1. ios::beg - start of the file
2. ios::cur - current position of the pointer
3. ios::end - end of the file

put( ) and get( ) functions

1. The function put( ) writes a single character to the associated stream.


2. The function get( ) reads a single character from the associated stream.

WAP TO WRITE AND READ FROM THE FILE CHARACTER BY


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

void main()
{
char string[100]; // creating a character array of size 100

cout<<"Enter the string";


cin>>string;

int len=strlen(string); // calculating the length of the entered string and storing it in variable len

fstream file; // creating the fstream class object


file.open("Text",ios::in|ios::out); // opening the file named “text” in the input and output mode
for(int i=0;i<len;i++) // write character by character of the input string to the file
file.put(string[i]);

file.seekg(0); //going to the start position

char ch;

while(file) // checking the end of file


{
file.get(ch); //getting the character from the file
cout<<ch; //displaying the character to the console or screen
}

getch();
}

write( ) and read( ) functions


1. The functions write( ) and read( ), unlike put( ) and get( ) functions handle
the data in the binary form. This means the values are stored in the disk file
in the same format in which they are stored in the internal memory.
2. The syntax for these functions is as follows:-
inf.read((char *) &V, sizeof(V));
outf.write((char *) &V, sizeof(V));

Write a program to count the number of lines in a file.


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

void main()
{
ofstream fout; //creating an output sream class object fout
int count=0; // initializing count variable to 0

fout.open("ABC"); //opening the file named “abc”


fout<<"My name is divya"<<endl; //writing to the file using object fout
fout<<"I like c++";
fout.close(); //closing the file in the write mode
ifstream fin; //creating the input stream object fin
fin.open("ABC"); //opening the file in the input mode named “abc”

while(fin.eof()==0)
{
char buffer[100];
fin.getline(buffer,100); //reading from the file line by line
cout<<buffer<<”\n”; //displaying to the screen
count++; //incrementing the value for count
}
fin.close(); //closing the file in the read mode

cout<<count;
getch();
}
Write a program to count the number of words in a file and display on
the screen.
#include<iostream.h>
#include<conio.h>
#include<fstream.h>

void main()
{
clrscr();
int count=0;

ofstream outf;
outf.open("ABC");
outf<<"My name is divya";
outf.close();

ifstream inf;
inf.open("ABC");

char buffer[100];
while(inf.eof()==0)
{
inf.getline( buffer, 100, ' ' ); //using getline delimiter (It will fetch character until ‘ ‘
is encountered or 100 characters are encountered)
cout<<buffer;
count++;
}

cout<<"\n Number of words are "<<count;


getch();
}

You might also like