0% found this document useful (0 votes)
65 views77 pages

7FILE HANDLING Ver7

The document discusses various functions for stream input and output in C++, including: 1. The input extraction operator (>>) removes whitespace and reads printable data until the next whitespace. 2. The get() function reads every character, printable or not. 3. The read() function requires a character pointer and integer size, reading a fixed number of characters without appending null. 4. The gets() function reads directly from keyboard without using the stream.

Uploaded by

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

7FILE HANDLING Ver7

The document discusses various functions for stream input and output in C++, including: 1. The input extraction operator (>>) removes whitespace and reads printable data until the next whitespace. 2. The get() function reads every character, printable or not. 3. The read() function requires a character pointer and integer size, reading a fixed number of characters without appending null. 4. The gets() function reads directly from keyboard without using the stream.

Uploaded by

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

Notes

Stream & File Handling


Stream
Characters are of two types: Version 7
1. Printable
2. Non Printable

White space =non printable characters = i.e. \t , \n ,


\r , space etc.

Stream input: All of the input given by the keyboard


goes to the stream. All the stream input, requires
enter (carriage return) (‘\n’) to be pressed to end the
input.
It stops taking the input when the requirement gets
fulfilled and it receives enter(‘\n’) after that.

Working of input operator (>>) (i.e. cin>>)  It


removes all the initial white space from the stream
and reads the matter (printable data) until the next
white space is encountered.

Page 1 of 77 Satpal Singh(9811969092) File Handling V7


Working of member function get(ch)  For the
function get( ), each and every character given (either
printable or non printable) is the input for it. It read
exactly one character from the stream and it assigns
it to its parameter (character variable).

read ( )
The member function of class istream requires
exactly 2 parameters.
1. The pointer to character (array of character)
2. integer (i.e. the number of character to read
from the stream)

It does not require any delimiter.


i.e.
char str[10];
cin.read(str,10);

The above example would read exactly 10 characters


form the keyboard in the str variable.

Unlike input operator (>>) the read function doesn’t


append a NULL character at the end of the string.

Page 2 of 77 Satpal Singh(9811969092) File Handling V7


Similarly the member function write( ) do also have
the two parameters.
cout.write (str,10);
Along with the read function we should use write
function (not output operator (<<))

i.e. don’t use  cout<<str;

The above statement would show the value of str


along with some garbage value, as NULL was not
appended to the string while reading the value in str
using the member function read( ).
The output operator displays the string until the
NULL is encountered.
i.e. The input given is abcdefghij
The output shell be abcdefghij43lks#@df

Functioning of input operator (>>)

#include<conio.h>
#include<iostream.h>
void main( )
Page 3 of 77 Satpal Singh(9811969092) File Handling V7
{
char a,b,c,d;
cout<<"\nEnter data1 ";
cin>>a>>b;
cout<<"a is "<<a<<" b is "<<b;
cout<<"\nEnter data2 ";
cin>>c>>d;
cout<<"c is "<<c<<" d is "<<d;
getch( );
}

Output:
Example 1 (Normal functioning):
Enter data1 k
l
a is k b is l
Enter data2 y
u
c is y d is u

Example 2:
Enter data1 rtyu
a is r b is t
Enter data2 c is y d is u

Page 4 of 77 Satpal Singh(9811969092) File Handling V7


Example 3:
Enter data1 g hk n
a is g b is h
Enter data2 c is k d is n

Example 4:
Enter data1 pou
a is p b is o
Enter data2 g
c is u d is g

Example 5:
Enter data1 kumari
a is k b is u
Enter data2 c is m d is a
// ri and enter is still in the stream.

Page 5 of 77 Satpal Singh(9811969092) File Handling V7


Functioning of member function get( )
#include<conio.h>
#include<iostream.h>
void main( )
{
char a,b,c,d,e,f;
cout<<"\nEnter data1 ";
cin.get(a);
cout<<"\nEnter data2 ";
cin.get(b);
cout<<"\nEnter data3 ";
cin.get(c);
cout<<"\nEnter data4 ";
cin.get(d);
cout<<"\nEnter data5 ";
cin.get(e);
cout<<"\nEnter data6 ";
cin.get(f);
cout<<"\na is "<<a<<" b is "<<b;
cout<<"\nc is "<<c<<" d is "<<d;
cout<<"\ne is "<<e<<" f is "<<f;
getch( );
}
Page 6 of 77 Satpal Singh(9811969092) File Handling V7
1st Example of output:
Enter data1 dust

Enter data2
Enter data3
Enter data4
Enter data5
Enter data6 kjh

a is d b is u
c is s d is t
e is
f is k

//jh and enter is still in stream.

Page 7 of 77 Satpal Singh(9811969092) File Handling V7


2nd Example of output: //input is //q space 1 enter

Enter data1 q 1

Enter data2
Enter data3
Enter data4
Enter data5 udcvbn

Enter data6
a is q b is
c is 1 d is

e is u f is d

//cvbn and enter is still in stream

//Note ASCII values A-65 B-66 C-67….. a-97 b-98


…. 0-48 1-49 2-50 …… 9-57
Combination of function get( ) and input operator
#include<conio.h>
#include<iostream.h>
void main( )
{
Page 8 of 77 Satpal Singh(9811969092) File Handling V7
char a,b,c,d,e,f,g[10],h[10];
cout<<"\nEnter data1 ";
cin.get(a);
cout<<"\nEnter data2 ";
cin.get(b);
cout<<"\nEnter string1 ";
cin>>g;
cout<<"\nEnter data4 ";
cin.get(d);
cout<<"\nEnter data5 ";
cin.get(e);
cout<<"\nEnter string2 ";
cin>>h;
cout<<"\na is "<<a<<" b is "<<b;
cout<<"\ng is "<<g<<" d is "<<d;
cout<<"\ne is "<<e<<" h is "<<h;
getch( );
}

Page 9 of 77 Satpal Singh(9811969092) File Handling V7


1st Example of output:

Enter data1 computer student tanvi

Enter data2
Enter string1
Enter data4
Enter data5
Enter string2
a is c b is o
g is mputer d is
e is s h is tudent
// space and tanvi and enter is still in stream

2nd Example of output:


Enter data1 hard work is the key of success

Enter data2
Enter string1
Enter data4
Enter data5
Enter string2
a is h b is a
g is rd d is
Page 10 of 77 Satpal Singh(9811969092) File Handling V7
e is w h is ork
// space is the key of success enter  is still in stream

cin. getline it have 3 parameters


1 string => char* => char[]
2 size => integer
3 delimiter => character (The default delimiter is ‘\n’
(new line))

1 string: getline( ) reads the string from the stream in


the string varible.
2. size: it is the intege value. getline( ) reads
maximum of size-1 characters from the stream.
3. delimiter: it is a character. As soon as the delimiter
is encountered it stops reading from the stream and
removes the delimiter from the stream
(throw away the delimiter from the stream.)
It read only the matter before the delimiter into the
string variable.
Its third parameter (i.e. the delimiter) is a default
argument having value '\n'
That means we may omit the third parameters while
invoking the function getline( )

Page 11 of 77 Satpal Singh(9811969092) File Handling V7


Page 12 of 77 Satpal Singh(9811969092) File Handling V7
Combination of function get( ) and getline( )
#include<conio.h>
#include<iostream.h>
void main( )
{
char a,b,c,d,e,f,g[10],h[10];
cout<<"\nEnter data1 ";
cin.get(a);
cout<<"\nEnter data2 ";
cin.get(b);
cout<<"\nEnter string1 ";
cin.getline(g,10);
cout<<"\nEnter data4 ";
cin.get(d);
cout<<"\nEnter data5 ";
cin.get(e);
cout<<"\nEnter string2 ";
cin.getline(h,10);
cout<<"\na is "<<a<<" b is "<<b;
cout<<"\ng is "<<g<<" d is "<<d;
cout<<"\ne is "<<e<<" h is "<<h;
getch( );
}
1st Example of output:
Enter data1 abcdefghijklmnop
Page 13 of 77 Satpal Singh(9811969092) File Handling V7
Enter data2
Enter string1
Enter data4
Enter data5
Enter string2
a is a b is b
g is cdefghijk d is l //10 means 9 characters
e is m h is nop ///default delimiter is enter

2nd Example of output:


Enter data1 abcde

Enter data2
Enter string1
Enter data4 fghijklmnopqrst

Enter data5
Enter string2
a is a b is b
g is cde d is f //and also the enter shell be
removed from the stream
e is g h is hijklmnop //9 characters

//qrst and enter is still in stream


Page 14 of 77 Satpal Singh(9811969092) File Handling V7
Detailed study of function getline( )
#include<conio.h>
#include<iostream.h>
void main( )
{
char a[20],b[20],c[20],d[20];
clrscr();
cout<<"\nEnter string 1 ";
cin.getline(a,20,'#');
cout<<"\nEnter string 2 ";
cin.getline(b,20,'r');
cout<<"\nEnter string 3 ";
cin.getline(c,20,'m');
cout<<"\nEnter string 4 ";
cin.getline(d,20);
cout<<"\nString 1 is "<<a<<"\nString 2 is "<<b;
cout<<"\nString 3 is "<<c<<"\nString 4 is "<<d;
getch( );
}

1nd Example of output:

Enter string 1 the inp#ut is controlled through the


computer

Page 15 of 77 Satpal Singh(9811969092) File Handling V7


Enter string 2
Enter string 3
Enter string 4
String 1 is the inp
String 2 is ut is cont
String 3 is olled through the c //It would read 19
(20-1) characters because 2nd argument is 20
String 4 is omputer

2nd Example of output:

Enter string 1 it is a t#est of cornor of computers

Enter string 2
Enter string 3
Enter string 4
String 1 is it is a t
String 2 is est of co
String 3 is nor of co
String 4 is puters

Page 16 of 77 Satpal Singh(9811969092) File Handling V7


3rd Example of output:

Enter string 1 abc#def

Enter string 2 gh
ijk
lmrstu

Enter string 3 computer

Enter string 4
String 1 is abc
String 2 is def
gh
ijk
lm
String 3 is stu
co
String 4 is puter

gets( )

Page 17 of 77 Satpal Singh(9811969092) File Handling V7


The library function gets( ) doesn’t read form the
stream. It reads the input directly from the keyboard.
It is a function of language ‘C’. Its header file is
stdio.h

#include<conio.h>
#include<iostream.h>
#include<stdio.h>
void main( )
{
char a,b,c,d,e,f,g[10],h[10];
cout<<"\nEnter data1 ";
cin.get(a);
cout<<"\nEnter data2 ";
cin.get(b);
cout<<"\nEnter string1 ";
gets(g);
cout<<"\nEnter data4 ";
cin.get(d);
cout<<"\nEnter data5 ";
cin.get(e);
cout<<"\nEnter string2 ";
gets(h);
cout<<"\na is "<<a<<" b is "<<b;
cout<<"\ng is "<<g<<" d is "<<d;
Page 18 of 77 Satpal Singh(9811969092) File Handling V7
cout<<"\ne is "<<e<<" h is "<<h;
getch( );
}

Page 19 of 77 Satpal Singh(9811969092) File Handling V7


Example of Output

Enter data1 abcdefghijklmnopq

Enter data2
Enter string1 tanvi//the data is there in stream but
gets( ) would read the data from the k/b

Enter data4
Enter data5
Enter string2 pancholi

a is a b is b
g is tanvi d is c
e is d h is pancholi //pancholi is given through k/b

//efghijklmnopq and enter is still in stream

Similarly getch( ) and function getche ( ) also read


input directly from the keyboard.
For the further explanations, wait for the next
version.
Page 20 of 77 Satpal Singh(9811969092) File Handling V7
Page 21 of 77 Satpal Singh(9811969092) File Handling V7
File Handling
character by character
i => input => read clue -> cin
o => output => write clue -> cout

Name of header file


fstream.h
There is no header file by the name of
ifstream.h or ofstream.h

Nme of the classes


ifstream
ofstream
fstream

modes
ios::in //for reading purpose
ios::out //creates a new file (or deletes the existing
text from the file)
if not used with ios::in or ios::app
ios::app always write at the end of the file
//modification of existing data is impossible
Page 22 of 77 Satpal Singh(9811969092) File Handling V7
ios::binary for binary files

Following are beyond the curriculum:


ios::trunc
ios::ate
ios::nocreate
ios::noreplace

Page 23 of 77 Satpal Singh(9811969092) File Handling V7


#include<fstream.h>
#include<conio.h>
void main( )
{
ofstream a("out.txt"); //invoking 1 arg constructor
/*
ofstream b;
b.open("out.txt");

//fstream c("out.txt");//error class fstream does


not contain 1 arg const

fstream d("out.txt",ios::out);

fstream e;
e.open("out.txt"); //error the member function
open of class fstream requires 2 args.

fstream e;
e.open("out.txt",ios::out);
*/
//if the file fails to open the value of the file
object automatically sets as NULL
if(!a) //if(a==NULL)
{
Page 24 of 77 Satpal Singh(9811969092) File Handling V7
cout<<"\nFile opening error ";
return;
}
a.put('t');
a.put('o');
a.put('y');
a<<’ ‘<<’i’<<’s’<<’ ‘;
a<<”soft”;
a.write(“and silky”,9);
a.close( );
}

The contents of file out.txt after execution of the


above code shell be:
Toy is soft and silky

Q How to open the file out.txt and see its contents in


the IDE Turbo C++
Ans Press F3 (or File -> Open) type out.txt and press
enter.
In order to close the file use alt+F3

Page 25 of 77 Satpal Singh(9811969092) File Handling V7


Assumption: While reading a text file word by word
or line by line, we shell assume that there is a new
line character (i.e. '\n')at the end of each text file.

Q Write a program to put a string "toy" over a text


file out.txt character by character.

#include<fstream.h>
#include<conio.h>
void main( )
{
ofstream a("out.txt"); //invoking 1 arg constructor
if(!a) //if (a==NULL)
{
cout<<"\nFile opening error ";
return;
}
a.put('t');
a.put('o');
a.put('y');
a.close( );
}

Page 26 of 77 Satpal Singh(9811969092) File Handling V7


//reading: Once read before the loop and one at the
end of the loop

Q Read some text from key board and write it over a


text file out.txt character by character until # is given
as input

#include<fstream.h>
#include<conio.h>
void main( )
{
ofstream a("out.txt"); //invoking 1 arg constructor
if(!a) //if (a==NULL)
{
cout<<"\nFile opening error ";
return;
}
char ch;
//reading : once read before the loop and one at
the end of the loop
cin.get(ch);
while(ch!='#') //while(ch!=EOF) //EOF control +
z shell be the delimiter
{
a.put(ch);
Page 27 of 77 Satpal Singh(9811969092) File Handling V7
cin.get(ch);
}
a.close( );
}
//If the input is “This is a good#school” The file
contents shell be “This is a good”

Warning: If we read only once inside the loop instead


of reading once before loop and once at the end of the
loop the delimiter # (which was not desired to be
written over the file) shell also be written in the text
file.

#include<fstream.h>
#include<conio.h>
void main( )
{
ofstream a("out.txt"); //invoking 1 arg constructor
if(!a) //if (a==NULL)
{
cout<<"\nFile opening error ";
return;
}
char ch;
Page 28 of 77 Satpal Singh(9811969092) File Handling V7
while(ch!='#')
{
cin.get(ch);
a.put(ch);
}
a.close( );
}

//If the input is “This is a good#school” The file


contents shell be “This is a good#”

Page 29 of 77 Satpal Singh(9811969092) File Handling V7


As we know that the computer automatically adds a
NULL character at the end of every string similarly a
EOF (end of file) pointer is automatically added by
the operating system at the end of each file.
//Let the contents of the text file out.txt is "Dear Students"

D e a r S t u d e n t s EO
ios::beg 0 1 2 3 4 5 6 7 8 9 10 11 12 13
- - - - - - - - - - - -
ios::end 13 12 11 10 9 8 7 6 5 4 3 2 -1 0

Q Display the contents of file out.txt over the screen


character by character.

#include<fstream.h>
#include<conio.h>
#include<ctype.h>
void main( )
{
clrscr( );
ifstream a("out.txt"); //invoking 1 arg constructor
if(!a) //if (a==NULL)
{
Page 30 of 77 Satpal Singh(9811969092) File Handling V7
cout<<"\nFile opening error ";
return;
}
char ch;
cout<<isdigit('t');
//Output shell be 0 (false) if the input is not in
between '0' and '9' (48-57) otherwise non zero
a.get(ch);
while(a.eof( )==0) //while(ch!='t')
{
//cout.put(ch);
cout<<ch;
a.get(ch);
}
a.close( );
getch( );
}

if we use while(ch!='t') instead of while(a.eof( )==0)


it would display the contents of the file until the first
‘t’ is encountered in the file.
Assuming that the file contents are
A keyboard is a standard input device.
The output shell be
A keyboard is a s
Page 31 of 77 Satpal Singh(9811969092) File Handling V7
Page 32 of 77 Satpal Singh(9811969092) File Handling V7
Methods of detecting end of file:
Method 1:Using member function eof( )i.e. while
(a.eof( )==0)
Method 2:Using member function eof( )i.e. while (!
a.eof( ))
As we know = = 0 is same as !
i.e.
if (strcmp (a,b)==0) cout<<" both string are
same ";
if (!strcmp (a,b)) cout<<" both string are
same ";
Above both of the statements are same.
Method 3:Detecting end of file without using
member function eof( ).
Use only the file object name instead
of the condition of loop.

#include<fstream.h>
#include<conio.h>
void main( )
{
clrscr( );
ifstream a("out.txt"); //invoking 1 arg constructor
if(!a) //if (a==NULL)
Page 33 of 77 Satpal Singh(9811969092) File Handling V7
{
cout<<"\nFile opening error ";
return;
}
char ch;
a.get(ch);
//while(a.eof( )==0) // best to
understand
//while(!a.eof( )) //it is most trendy
//as soon as the object fails to read, the value of
its object
//automatically sets as NULL
while(a) //Method 3 //it should be
avoided
{
//cout.put(ch);
cout<<ch;
a.get(ch);
}
a.close( );
getch( );
}

Page 34 of 77 Satpal Singh(9811969092) File Handling V7


Page 35 of 77 Satpal Singh(9811969092) File Handling V7
Method 4:Instead of //Best
1. reading once before the loop
2. Once at the end of the loop and
3. Using member function eof( ) as a
condition of the loop
Use
Reading statement at the place of loop
condition.

#include<fstream.h>
#include<conio.h>
void main( )
{
clrscr( );
ifstream a("out.txt"); //invoking 1 argument
constructor
if(!a) //if (a==NULL)
{
cout<<"\nFile opening error ";
return;
}
char ch;
Page 36 of 77 Satpal Singh(9811969092) File Handling V7
while(a.get(ch))
cout<<ch;
a.close( );
getch( );
}

Q Read the contents of file cpu.txt and write it over


another text file cpu2.txt by converting all lower case
character to upper case.
#include<fstream.h>
#include<conio.h>
#include<ctype.h>
void main( )
{
clrscr( );
ifstream r("CPU.TXT");
ofstream w("cpu2.txt"); //invoking 1 arg
constructor
if(!r || !w) //if (r == NULL || w == NULL)
{
cout<<"\nFile opening error ";
return;
}
char ch;
Page 37 of 77 Satpal Singh(9811969092) File Handling V7
while(r.get(ch))
w.put(toupper(ch)); //w<<toupper(ch);
r.close( );
w.close( );
}

Page 38 of 77 Satpal Singh(9811969092) File Handling V7


instead of
while(r.get(ch))
w.put(toupper(ch)); //w<<toupper(ch);
you may use
while(r.get(ch))
{
ch=toupper(ch);
w.put(ch);
}

Define a function named as count( ) having a text


file name as its parameter. The function will have to
display the number of upper case alphabets, number
of digits, number of spaces and number of newlines
in this text file.

#include<conio.h>
#include<fstream.h>
#include<ctype.h>
void count(char fn[]) //fn is formal
parameter
{
Page 39 of 77 Satpal Singh(9811969092) File Handling V7
ifstream fin(fn);
if(!fin)
{
cout<<"\nFile opening error ";
return;
}
int u=0,d=0,s=0,n=0;
char ch;
while(fin.get(ch))
{
if(isupper(ch)) //if(ch>='A' && ch<='Z')
u++;
if(isdigit(ch)) //if(ch>='0' && ch<='9')
d++;
if(ch==' ')
s++;
if(ch=='\n')
n++;
}
cout<<u<<"\t"<<d<<"\t"<<s<<"\t"<<n;
fin.close( );
}

void main( )
{
Page 40 of 77 Satpal Singh(9811969092) File Handling V7
clrscr( );
count("mouse.txt"); //mouse.txt is the
actual parameter
getch( );
}

Member functions of class ifstream


seekg(bytes,position);
tellg( );
The ‘g’ in seekg( ) or tellg( ) refers to get pointer.
g->get->read->ifstream
Similarly the ‘p’ in seekp( ) or tellp( ) refers to put
pointer. p->put->write->ofstream

The seekg ( ) function requires two parameters


1. The number of bytes to move (integer)
2. From the position (ios::beg, ios::cur, ios::end)
ios::beg is the default value (i.e. the second
argument is default argument having value
ios::beg)

ios::beg require 0 or positive value (i.e. value>=0)


ios::end require 0 or negative value (i.e.
value<=0)
Page 41 of 77 Satpal Singh(9811969092) File Handling V7
ios::cur may have any –ive or +ive value
depending on the current position of the file
pointer.

The function tellg( ) doesn’t have any parameter. It


simply returns the current file pointer position. It
always count from the beginning.

Both of them are the member functions, so don’t ever


use any of them without an object name.
i.e.
int x=fobj.tellg( ); //returns the current position of the
pointer in the file.
fobj.seekg(10,ios::cur); //to move 10 bytes ahead
from the current position.

Member function of class ofstream


seekp( )
tellp( )

While using the object of class fstream we may use


any of the four functions.
For the object of class fstream, member functions
seekg( ) and seekp( ) both would work identical
Page 42 of 77 Satpal Singh(9811969092) File Handling V7
and similarly tellg( ) and tellp( ) would perform the
same job.

The following function names are there in all the


three classes (i.e. fstream, ifstream and ofstream)
open( ) close( ) eof( ) etc

Member Functions beyond the curriculum: good( ),


bad( ), fail ( ) etc

Page 43 of 77 Satpal Singh(9811969092) File Handling V7


#include<fstream.h>
#include<conio.h>
#include<ctype.h>
void main( )
{
clrscr( );
fstream w("cpu.txt",ios::in | ios::out);
char ch,str[30];
cout<<"\nThe current position is : "<<w.tellg( );

w.seekg(2); //w.seekg(2,ios::beg);
cout<<"\nThe current position is : "<<w.tellg( );
w.put('Q');
cout<<"\nThe current position is : "<<w.tellg( );
w.seekp(1);
w.put('A'); //w.seekg(2,ios::beg);
cout<<"\nThe current position is : "<<w.tellg( );
w.seekp(3,ios::cur);
w.put('F');
cout<<"\nThe current position is : "<<w.tellg( );

w.seekp(-3,ios::end);
w.put('R');
cout<<"\nThe current position is : "<<w.tellg( );

Page 44 of 77 Satpal Singh(9811969092) File Handling V7


w.close( );
}
Let the contents of the text file cpu.txt is "Dear Students"

D e a R S t u d e n t s EO
ios::beg 0 1 2 3 4 5 6 7 8 9 10 11 12 13
- - - - - - - - - - - -
ios::end 13 12 11 10 9 8 7 6 5 4 3 2 -1 0
Let the contents of the text file cpu.txt is "Dear Students"

D A Q r F t u d e R t s EO
ios::beg 0 1 2 3 4 5 6 7 8 9 10 11 12 13
- - - - - - - - - - - -
ios::end 13 12 11 10 9 8 7 6 5 4 3 2 -1 0

Output:
The current position is : 0
The current position is : 2
The current position is : 3
The current position is : 2
The current position is : 6
The current position is : 11

Contents of cpu.txt
DAQr FtudeRts

Page 45 of 77 Satpal Singh(9811969092) File Handling V7


Q Define a function named as replace( ) having three
parameters
1 text file name
2. characte ch1
3. character ch2
The function is required to replace every
occurrence of ch1 with ch2 in the
text file.

#include<fstream.h>
#include<conio.h>
#include<ctype.h>
void replace(char fn[],char x, char y)
{
char ch;
//clrscr( );
fstream w(fn,ios::in | ios::out); //invoking 1 arg
constructor
while(w.get(ch))
if(ch==x)
{
w.seekg(-1,ios::cur);
w.put(y);
}
Page 46 of 77 Satpal Singh(9811969092) File Handling V7
w.close( );
}
void main( )
{
char a[30],b,c;
cout<<"\nEnter file name and 2 characters ";
cin>>a>>b>>c;
//replace("cpu.txt",'t','Z');
replace(a,b,c);

No header file and no main( ) is required to write in


your answer sheet in your examination. Only the
body of the function replace( ) is required(i.e. the
bold text above).

Page 47 of 77 Satpal Singh(9811969092) File Handling V7


Q Define a function named as toggle( ) having a text
file name as its parameter. The function is required to
toggle the case (change lower case to upper case and
change upper case to lower case) of all the alphabets
used in the file and the function would replace every
digit with its next digit i.e. change 0 to 1, 1 to 2 ... 9
to 0
i.e. if the file contents are:
The sum of 50 + 60 IS 110
The contents of the file after execution of the code
should be:
tHE SUM OF 69 + 79 is 229

#include<fstream.h>
#include<conio.h>
#include<ctype.h>
void toggle(char fn[])
{
char ch;
fstream w(fn,ios::in | ios::out); //invoking 1 arg
constructor
while(w.get(ch))
{
if(isupper(ch))
{
Page 48 of 77 Satpal Singh(9811969092) File Handling V7
w.seekg(-1,ios::cur);
w.put(tolower(ch));
}
else
if(islower(ch))
{
w.seekg(-1,ios::cur);
w.put(toupper(ch));
}

else
if(isdigit(ch))
{
w.seekg(-1,ios::cur);
if(ch=='9')
w.put('0');
else
w.put(ch+1);
}
}
w.close( );
}
void main( )
{
char a[30];
Page 49 of 77 Satpal Singh(9811969092) File Handling V7
cout<<"\nEnter file name ";
cin>>a;
toggle(a);
}

Page 50 of 77 Satpal Singh(9811969092) File Handling V7


Word by Word

Q Read the contents of file cpu.txt and display its


words along with their word number.
i.e. if the file contents are:
It is language C++.
It is an example of OOP.

The output should be:


It 1
is 2
language 3
C++. 4
It 5
is 6
an 7
example 8
of 9
OOP. 10

#include<fstream.h>
#include<conio.h>
#include<ctype.h>
void main( )
{
Page 51 of 77 Satpal Singh(9811969092) File Handling V7
char a[30];
int count=0;
clrscr( );
fstream r("cpu.txt",ios::in);
while(r>>a)
{
cout<<a;
cout<<" "<<++count<<endl;
getch( );
}
getch( );
}

Page 52 of 77 Satpal Singh(9811969092) File Handling V7


Q Display the contents of file cpu.txt after removing
all non printable characters. (i.e. all the contents are
to be displayed in the same line without any space or
newline or tab etc.) and also display the number of
words present in it.
i.e. if the file contents are:
It is language C++.
It is an example of OOP.

The output should be:


itislanguageC++.ItisanexampleofOOP.
The number of words is 10

#include<fstream.h>
#include<conio.h>
#include<ctype.h>
void main( )
{
char a[30];
int count=0;
clrscr( );
fstream r("cpu.txt",ios::in);
r>>a;
while(r.eof( )==0) //while(!r.eof( ))
{
Page 53 of 77 Satpal Singh(9811969092) File Handling V7
count++;
cout<<a;
r>>a;
}
cout<<”\nThe number of words is “<<count;
getch( );
}

Q Display the contents of file cpu.txt over the screen


word by word.
#include<fstream.h>
#include<conio.h>
void main( )
{
char a[30],ch;
clrscr( );
fstream r("cpu.txt",ios::in);
r>>a;
r.get(ch);
while(r.eof( )==0) //while(!r.eof( ))
{
cout<<a<<ch;
r>>a;
r.get(ch);
}
Page 54 of 77 Satpal Singh(9811969092) File Handling V7
getch( );
}

Q Write a name akash garg over a text file named as


t.t
#include<fstream.h>
#include<conio.h>
void main( )
{
char a[30],ch;
clrscr( );
fstream fout("t.t",ios::out);
fout<<"akash"<<" garg";
fout.close( );
}

Q Define a function having 2 file names as its


parameter. The function would copy all words
beginning with 't' or 'T' from the source file to the
target file and return the number of words copied.

Example
Contents of the source file:
The students of the class twelfth
are teenagers and they
Page 55 of 77 Satpal Singh(9811969092) File Handling V7
should trust themself as they are the best.

Contents of the target file:


The the twelfth teenagers they trust themself they the

Output
9

#include<fstream.h>
#include<conio.h>
int copy(char f1[],char f2[])
{
char a[30];
clrscr( );
fstream r(f1,ios::in);
fstream w(f2,ios::out);
int count=0;
while(r>>a)
if(a[0]=='t' || a[0]=='T')
{
count++;
w<<a<<" ";
}
return count;
}
Page 56 of 77 Satpal Singh(9811969092) File Handling V7
void main( )
{
cout<<copy("a.a","b.b");
getch( );
}

Page 57 of 77 Satpal Singh(9811969092) File Handling V7


Line by Line
Q Define a function named as copy ( ) having 2 file
names as its parameter. The function would copy the
contents of first file to the second file line by line and
the function would return the number of lines present
in the source file.

#include<fstream.h>
#include<conio.h>
int copy(char f1[],char f2[])
{
char string[80];
clrscr( );
fstream r(f1,ios::in);
fstream w(f2,ios::out);

int count=0;
while(r.getline(string,80))
{
count++;
w<<string<<'\n';
}
Page 58 of 77 Satpal Singh(9811969092) File Handling V7
return count;
}
void main( )
{
cout<<copy("a.a","b.b");
}

the ‘\n’ in the statement w<<string<<'\n';


is mandatory
i.e. the function getline( ) would remove the \n from
the stream and even it shell not be placed in the string
variable named as string
If \n is not used, all of the lines on the target file shell
be there in the same line.

Page 59 of 77 Satpal Singh(9811969092) File Handling V7


Binary File Handling
Q Given a sturcture emp.
struct emp
{
int eno;
char name[98];
};
Define a function ABC( ) writing N number of
record of sturcture emp to the
binary file emp.dat where N it the parameter to
the function.

#include<conio.h>
#include<fstream.h>
#include<process.h>
struct emp
{
int eno;
char name[98];
};

void ABC(int N)
{
Page 60 of 77 Satpal Singh(9811969092) File Handling V7
ofstream fout("emp.dat",ios::binary);
// fstream fout("emp.dat",ios::binary | ios::out);

if(!fout)
{
cout<<"\nFile opening error";
exit(0); //process.h
}
emp x;
for(int i=0;i<N;i++)
{
cout<<"\nEnter emp and name : ";
cin>>x.eno>>x.name; //x.get_data( ) if
emp is class
fout.write((char*)&x,sizeof(emp));
//fout.write((char*)&x,sizeof(x));
}
fout.close( );
}

void main( )
{
clrscr( );
int N;
cout<<"\nEnter the number of records : ";
Page 61 of 77 Satpal Singh(9811969092) File Handling V7
cin>>N;
ABC(N);

Q Assuming the a binary file emp.dat already exist.


It is containing the records of the structure emp
given below:
struct emp
{
int eno;
char name[98];
};
Define a function Display( ) displaying all the
records from this binary file

#include<conio.h>
#include<fstream.h>
#include<process.h>
struct emp
{
int eno;
Page 62 of 77 Satpal Singh(9811969092) File Handling V7
char name[98];
};

void Display( )
{
ifstream f("emp.dat",ios::binary);
if(!f)
{
cout<<"\nFile opening error";
exit(0);
}
emp x;
while(f.read((char*)&x,sizeof(emp))) //three
close parenthesis sizeof, read, while
cout<<"\nThe emp and name : "<<x.eno<<"
"<<x.name;
//x.show_data( ) if emp is a class
f.close( );
}

void main( )
{
clrscr( );
Display( );
getch( );
Page 63 of 77 Satpal Singh(9811969092) File Handling V7
}

Page 64 of 77 Satpal Singh(9811969092) File Handling V7


Q Assuming the a binary file emp.dat already exist.
It is containing the records of the structure
emp given below
struct emp
{ int eno;
char name[98];
};
Define a function Modify( ) modifying the Nth
record where the N is the parameter to the
function

#include<conio.h>
#include<fstream.h>
#include<process.h>
struct emp
{
int eno;
char name[98];
};

void Modify(int N)
{
fstream f("emp.dat",ios::binary | ios::in | ios::out);
if(!f)
{
Page 65 of 77 Satpal Singh(9811969092) File Handling V7
cout<<"\nFile opening error";
exit(0);
}
//count the total number of records existing in the
binary file

int s=sizeof(emp);
f.seekp(0,ios::end);
int pos=f.tellp( );
int records=pos/s;
if(N>records)
{
cout<<"\nThe total number of records in the
file is "<<records;
cout<<"\nPlease enter the number
<="<<records;
exit(0);
}
emp x;
cout<<"\nEnter emp and name for new record : ";
cin>>x.eno>>x.name; //x.get_data( ) if x is an
object of class emp
f.seekp(s*(N-1));
f.write((char*)&x,sizeof(emp));
cout<<"\nRecord Modified ";
Page 66 of 77 Satpal Singh(9811969092) File Handling V7
f.close( );
}

Page 67 of 77 Satpal Singh(9811969092) File Handling V7


void main( )
{
int r;
clrscr( );
cout<<"\nEnter record number to modify : ";
cin>>r;
Modify(r);
getch( );

Q A file student.dat contains four data members viz.


name,rollno,marks and grade. Out of these
name and rollno have the values but marks and
grade have been left blank. Write a C++ function,
that reads the student records in objects of
following class STUD from the file student.dat:
class STUD {
int rollno;
char name[20];
float marks;
char grade;
public:
STUD(int k,char *s)
{
Page 68 of 77 Satpal Singh(9811969092) File Handling V7
rollno=k;
strcpy(name,s);
marks=0;
grade=’ ‘;
}
void getmarks( )
{
cout<<”Enter marks “;
cin>>marks;
}
void calcgrade( )
{
if(marks>=75) grade=’A’;
else if(marks>=60) grade=’B’;
else if(marks>=50) grade=’C’;
else
grade=’D’;
}
};
After reading the STUD objects from the file,
get students’ marks from the user, calculate
grade and then write back all the data back into
the same file.

Page 69 of 77 Satpal Singh(9811969092) File Handling V7


Ans:
void modify( )
{
fstream fobj("student.dat",ios::in|ios::out|
ios::binary);
STUD SS;
if(!fobj)
{
cout<<"\nFile opening error";
return;
}
int bytes=sizeof(STUD);
while(fobj.read((char*)&SS,sizeof(STUD)))
{
SS.getmarks( );
SS.calcgrade( );
fobj.seekp(-1*bytes, ios::cur);
fobj.write((char*)&SS,sizeof(STUD));
}
}
OR
Ans:
void modify( )
{

Page 70 of 77 Satpal Singh(9811969092) File Handling V7


fstream fobj("student.dat",ios::in|ios::out|
ios::binary);
STUD SS;
if(!fobj)
{
cout<<"\nFile opening error";
return;
}
int bytes=sizeof(STUD);
int recno=0;
while(fobj.read((char*)&SS,sizeof(STUD)))
{
SS.getmarks( );
SS.calcgrade( );
fobj.seekp(recno*bytes); //
fobj.seekp(recno*bytes,ios::beg);
fobj.write((char*)&SS,sizeof(STUD));
recno++;
}
}

Page 71 of 77 Satpal Singh(9811969092) File Handling V7


Extra
//Let the contents of the text file cpu2.txt is "Dear
Students"
#include<fstream.h>
#include<conio.h>
#include<ctype.h>
void main( )
{
clrscr( );
fstream w("cpu2.txt",ios::out | ios::in | ios::app);
//fstream w("cpu2.txt",ios::in | ios::app);
//above both are same
//fstream w("cpu2.txt",ios::out | ios::in);
//ofstream w("cpu2.txt",ios::in);
//ifstream w("cpu2.txt",ios::out);
// above 3 statements are same.
//fstream w("cpu2.txt",ios::out);

char ch='T';
w.put('K');
w.put(ch);
w.put(ch);
Page 72 of 77 Satpal Singh(9811969092) File Handling V7
w.close( );
}

Page 73 of 77 Satpal Singh(9811969092) File Handling V7


Explanation of white space
The member function isspace( ) returns 0 if the
parameter is not a white space otherwise it returns a
non-zero value i.e. 1
#include<iostream.h>
#include<conio.h>
#include<ctype.h>
void main( )
{
int a;
char b;
clrscr( );
cout<<"\nEnter an integer : ";
cin>>a;
cout<<"\nEnter a character : ";
cin>>b;
cout<<"\na is "<<a<<" b is "<<b<<endl;
cout<<isspace('\t');//ASCII 9
cout<<isspace('\n');//ASCII 10

cout<<isspace('\r');//ASCII 13
cout<<isspace(' ');//ASCII 32

cout<<"\nout 1 "<<isspace(9);
cout<<"\nout 2 "<<isspace(10);
Page 74 of 77 Satpal Singh(9811969092) File Handling V7
cout<<"\nout 3 "<<isspace(11);
cout<<"\nout 4 "<<isspace(12);
cout<<"\nout 5 "<<isspace(13);
cout<<"\nout 6 "<<isspace(32);
cout<<"\nout 7 "<<isspace('A');//0
getch( );
}

Output:
Enter an integer :

3445 mouse

Enter a character :
a is 3445 b is m
1111
out 1 1
out 2 1
out 3 1
out 4 1
out 5 1
out 6 1
out 7 0
Note: ouse + enter is still in the stream.
Page 75 of 77 Satpal Singh(9811969092) File Handling V7
put( )
Note: The put( ) function would write the output to
the output stream and the cout would flush the
stream.or the stream shell be flush automatically
when the program would terminate.

#include<conio.h>
#include<iostream.h>
void main( )
{
int a=99;
clrscr( );
cout.put(a++);
cout.put(a++);
cout.put(a++);
getch( ); //nothing shell be displayed till
this point
cout<<"";
getch( ); //the output cde shell be visible
cout.put(a++);
cout.put(a++);
cout.put(a++);
cout.put(a++);
Page 76 of 77 Satpal Singh(9811969092) File Handling V7
getch( ); //still the output only cde is visible
//the rest of the output i.e. fghi is still
in output stream
//it shell be flushed automatically as
soon as the program would
//terminate
}

Ultimate Output: (use alt + F5 to see the output)


cdefghi

Code segment:

cout<<endl<<ios::in; //1
cout<<endl<<ios::out;//2
cout<<endl<<ios::app; //8
cout<<endl<<ios::binary;//128
//The multiple modes can be used together using |
(bit-wise OR) (Pipe symbol)

Page 77 of 77 Satpal Singh(9811969092) File Handling V7

You might also like