File - Handling (Stream I/O) : Flow of Data

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 21

FILE – HANDLING (STREAM I/O)

Flow of data

if flow of data is from program towards device then o/p stream eg. cout . is used.

if flow of data is from device to program then i/p stream eg cin is used.

Monitor / Buffer Monitor

Input stream output stream

C++ Program

Input stream output stream

Hard-disk Hard disk

Classes Available In C++ for File Handling

1. Of Stream:- if a class whose objects can be created for writing data to


secondary memory of file.

2. It Stream:- is a class whose objects can be created for reading data


from file.

3. Fstream :- whose object can read / write the data in a file.

Steap Required for Writing Data In File

Step  1 Create the object of “Of stream” class


Eg:- Of stream obj;
Step 2 Connect the object with file on your system.
Step 3 write the data through the object in file.
Step 4 Close the file.

C++ Implement Of Above Steps

Step 1 (a) Of stream obj;


Step 2 obj. Open ( “Data. Txt”);
Step 3 (a) obj << “Hello”;
(b) obj. put (‘H’);
Step 4 obj.close ( );

1 (a) Of stream Obj ( “Data, txt”);


2(a) Of stream obj; clas static data
Bj.open (“Data. Txt”, ios : : app)
File Opening Mode

3 Of stream obj ( “Data. Txt”, ios : : app)

Step for Creating A Program for Reading A File

1. Create the object of “ifstream” class.


2. Connect the object with the file on your system & check whether file is
available or not.
3. Read the data through object from file.
4. class file.

C++ IMPLEMENTATION

1. if stream obj
2. (a) Obj. Open ( “Data.txt);
Or
if stream obj;
Obj.open ( “Data. Txt”, ios : : in);
Or
if stream obj (“Data.txt”, ios: : in);

Creating Object Of fstream class

1. fstream obj;
Obj.open ( “Data.text”, ios : : out | ios : : in);
2. Using Constructor
Fstream obj ( “Data.txt”, ios : : out | ios : : in);

WAP to create a file c/a “message. text” Accept a line of text from user & write it
in file character by character

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

void main ( )
{
Of stream out ( “Message. Text”);
if (!out)
{
cout << “file can not be opened”;
Getch ( );
exit(1);
}
char str[80];
cout << “enter a line of text”;
cin.qetline (str, 80);
int i=0;
While (str[i])
{
Out.put (str[i]);
I++;
}
cout << “file written successfully”;
Getch ( );
Out. Close( );
}

1
Note:- isopen ( ) Returns 1 if conceted
0
1
Fail( ) Retruns I if not connected
0
Que:- WAP to open the file created by the previous program. Read it on character
by character basic & display its contents on the screen.

Solution :-
void main ( )
{
if stream in ( “message.txt”);
if (! in)
{
cout << “filoe can not be opened”;
exit(1);
}
char ch;
While (! In.enf( ) )
{
Ch=in.get( );
cout << ch;
}
Getch( );
In.close( );
}

Que:- WAP to open a file c/a “Data.txt”. Accept a line of text from user & write it
on file character by character basic and it in the same program read file and print
its content on the screen .

void main( )
{
Fstream Nisha ( “Data”, ios: : out | ios: : in);
if (! Nisha)
{
cout << “error opening file”;
exit(1);
}
char str [80];
cout << “enter a line of text”;
cin.get line (str, 80);
int i=0;
char ch;
While (str [i])
{
Ch=str[i];
Obj.put (ch);
I++;
}
Obj.seekg (0);
While (! Obj.eof( ) )
{
Ch=obj.get( );
cout << ch;
}
Getch( );
Obj. close( );
}

Que  Assume there is a file c/a “Message. Txt” containing certain line of txt.
Create a file c/a “Message2.txt, and copy the contents of “messages.txt” into it.
Before coping the character must be converted upper to lower & vice versa &
spaces must be skipper. Finally display the contents of “Message2 txt”.

void main( )
{
if stream obj1 ( “Messages.txt”);
Stream obj2 (“Message2. txt”, ios : : out | ios : : in);
char ch;
if (! Obj1)
{
cout << sourcl file cant be opened”;
exit(1);
}
While (! Obj1, eof)
{
Ch = obj1. get( );
if (ch! = 32)
{
if (ch>=65 & & ch<=90)
Ch=ch+32;
else if (ch > =97 && ch <=122)
Ch=ch-32;
}
Obj2.put(ch);
}
Obj2.seekg(0);
While ( ! obj2. eof( ) )
{
Ch=obj2. get( );
cout << ch;
}
Getch( );
Obj2.closs( );
Obj1. close( );
}

READING AND WRITING STRINGS

void main ( )
{
Fstream obj ( “Data.txt”, ios : : out | ios : : in);
if !(!obj)
{
cout << “error”;
exit (1);
}
char text [80];
cout << “how many lines”;
int n;
cin >> n;
cout << “Enter “ << n<< “lines each terminated by enter : “<<end1;
for (in i=1; i<=n; i++)
{
cin.get line (text, 80);
Obj << text << end1;
}
Obj. seekg (0);
cout << “File written press nay key to read”;
Gecth( 0;
While (!obj.eof( ) )
{
Obj.getline (text,80);
cout << text << end1;
}
Gecth( );
Obj.close( );
}
void main( )
{
Fstream obj ( “Data.txt”, ios : : out | ios : : in);
if (!obj)
{
cout << “error”;
exit(1);
}
char text [80];
cout << “enter lines and press enter on new line to stop”;
While (1)
{
cin.getline (text, 80);
if (strlen (text) = =0)
Break;
Obj << text << end1;
}
}

FILE OPENING MODES

1. ios : : out (Default mode of ofstream)


if file is not existing then it is created. Otherwise data gets
Erased and pointer is placed at the beginning.

2. ios : : in
if file is existing, pointer is placed a the beginning otherwise
error is generated.
3. ios : : app
It can not alter previous contents but can add new content at the
End of file.

4. ios : : ate (ate stands for at the end)


Allows updations as well as adding of new data.
In this pointer can move forward and backward.
5. ios : : trunc
Needed only in fstream.
Used with ios : : out
Truncate previous data & brings pointer to beginning.

6. ios : : nerplace
Used with ios : : out if file is existing do not replace it otherwise
create it.

7. ios : : nocreate
Used with ios : : out if file is existing overwrite it otherwise do not
create it.

8. ios : : binary
if we want to write data in binary form.

BINARY I /O

void write (char *, int )


Of stream address of variable no of bytes to be written
Member whose data is to be
Written

int a = 23091 ;
Obj, write (( char *) &a, size of (int) );

char b = ‘x’;
Obj.seekg(0);
int c;
Obj. read ( (char *) &c, size of (int ) );
cout << c;
char d;
Obj. read (&d, size of (char) );
cout <<d;
int read (char *, int)
Address of variable whose data is to be stored after reading
From file
On successfully reading from file it returns 1 on error it return 0.
Reading and writing class objects

class Emp
{
int age;
char name [20];
float sal;
public:
void get( )
{
cout << “ enter age, name and sal”;
cin >> age >> name>> sal;
}
void show( )
{
cout << age << “ “ <<name << “ “ sal <<end1;
}
};

void main ( )
{
Emp E;
Fstream obj ( “Records.dat”, ios : : out | ios : : in | ios : : trunc| ios : :
Binary );
if (! Obj)
{
cout << “error in opening file”;
exit (1);
}
E.get( );
Obj.write ((char *) &E, size of (Emp) );
Obj.seekg(0);
Emp F;
Obj.read ((char *) &F, size of (Emp));
F.show( );
Getch( );
Obj.close( );
}
Reading And Writing Multiple Objects

void main ( )
{
Emp E;
Fstream obj ( “Record.dat’, ios: : out| ios : : in | ios : : trunc | ios : :
Binary);
if (! Obj)
{
Out << “error in opening file”;
exit (1);
}
char choice;

{
e.get( );
obj.write ((char *) &E, size of (Emp));
cout << “Any More (Y/N)”;
cin.ignore( );
cin >> choice;
} while ( ch = = ‘y’);
Obj. seekg (0);
While (opj.read (char *) &E, size of (emp))
E.show( );
getch( );
obj.close( );
}

Typical Feature Of Read:-

Note :- if in any ane program, we want to read file successively to eof


we must clear the flag
Obj. seekg (0);
Obj. clear( );

Q. WAP to write multiple records of type emp in a file. Accept a name from user
& display the record of the employee by searching it with in the file and display
the appropriate message

void main( )
{
int flat = 0
Emp E;
Fstream obj1 ( “Ekta, txt”, ios : : out | ios : : in | ios : : trunc |
Ios : ; binary);
if (! Obj)
{
cout << “error”;
exit(1);
}
char ch;
Do
{
E.get( );
Obj.write ( ( char *) &E, size of (Emp));
cout << “Ant more (y/n)”;
cin . ignore ( );
} while (ch = = ‘Y’);
char name [20];
cout << “enter name to search”;
cin >> name;
Obj. seekg(0);

While (obj.read (char *) &E, size of (emp))


{
if ( ! ( E = = name) )
{
E. show( );
Flag =1;
Break;
}
}
if ( ! flag) or if (flag = =0)
{
cout << “ Record not found”;
Obj1. close( );
}
int operator = = (char * ptr)
{
Return (strcmp (name, ptr) );
}
}

RANDOM I/O

Q. Assume there is a file c/a “Record.dat” which contains several records of type
emp. WAP to open this file & read the last record.

void main ( )
{
ifstream in ( “Records.dal”, ios : : in | ios : : binary);
if ( ! in)
{
cout << “error”;
exit (1);
}
In.seekg (-1 * size of (emp), ios : : end);
Emp E;
In. read ( ( char *) &E, size of (emp));
E.show( );
In.close( );
Getch( );
}

Note:- Prototype of seekg( )


void seekg (int, int)
No, of position of movement
Bytes to ios : : beg
Move ios : : cur
Ios : : end

WAP to accept a name from user. Search the record of that employee in
“Records.dat” & Add a new record at its position by accepting it from user

void main( )
{
char temp[20];
Emp E;
Fstream in ( “Records.dat”, ios : : in | ios : : ate| ios : : binary);
cout << “enter name to update”;
cin >> temp;
In.seekg(0);
While (in.read ( (char *) &E, size of (emp) )
{
if ( ( E = =temp) = =0)
{
E.get( );
In.seekg (-1 * size of (Emp), ios : : cur);
In.write ( ( char *) &E, size of (emp));
Breack;
}
}
In.clear( );
In.seekg(0);
While (in.read ( ( char *) &E, size of (Emp) )
E.show( );
int operator = =(char *n)
{
Return (strcmp (temp, ptr) );
}
}

Assignment :-

1. WAP to delete record given by user from file.


2. WAP to update just the salary of employee whose name given by user.

CONSOLE I/O OPERATIONS

Unformatted Formatted
1. Unformatted I/O
(a) istream & get (char &) can be
(b) int get( ) called by cin
(c) istream & get (char *, int)

Example :- cin.get(ch);
Can read only characters
cin=cin.get( );

Istream & getline (char *, int num, char delimiter);


Istream & getline (char *, int num);

Example :-

void main ( )
{
char ch;
cout << “enter text and press enter to stop”;
cin. Get (ch);
While (ch ! =’\n’)
{
cout << ch;
cin.get(ch);
}
Getch( );
}

void main ( )
{
char country [20], capital [20];
cout << “enter country name:”;
cin.get (country,20); cin.getline (country, 20);
cout << “enter capital”;
cin.getline (capital, 20);
cout << “contry is “<< country << end1;
cout << “its capital = “<< capital << end1;
}

Note:- cin.getline (country, 20, *)


This will terminate after 19 character or on pressing *, nothing
will happen on pressing enter rey.

Functions Of Ostream class


(a) ostream & put (char)
(b) ostream & write (char *, int)
This will start from base add upto no. of integers given.

Example :-
void main( )
{
char str[ ] = { “programming “};
int I;
for (i=0; i<strlen (str); i++)
{
cout.put (str [i]);
cout << end1;
}
for (i=1; i<=strlen(str); i++)
{
cout.write (str, i);
cout << end1;
}
for (i=strlen (str) ; i>=1; i--)
{
cout.write (str, i);
cout << end1;
}
}

FORMATTED I/O

Function Description

(i)width( ) specifies required no of fields to be used for displaying


the output. This fn is used for alignment.

(ii) precision( ) specifies the no of values to be displayed after decimal pt


(iii) fill( ) specifies a character to be used to fill the unused area of
field. By default the fulling is done using spaces.

(iv) setf( ) sets the format flag to be used while displaying the
output.

(v) unsetf( ) clears the flogs set using setf & restones the default
settling.

Defining field Width

Prototype:- int width( )


Returns the current width.
int width (int)
Old width aurrent width

void main( )
{
cout. Width(4);
cout << 123;
cout.width(4);
cout. << 39;
cout.width(2);
cout << 2345
}

Setting Precision

Prototype :-int precision ( ) By default


int precision (int) precision is of 6 pt.

void main ( )
{
cout precision (2);
cout << 2.23 << end1;
cout << 5. 169 << end1;
cout << 4.003 << end1;
}
Output  2,23
5.17
4

Filling :-
int fill( )
int fill (char)

void main( )
{
cout.file ( ‘*’);
cout.precision(2);
cout.width(6);
cout << 12.53;
cout.width(6);
cout << 20.5;
cout. width(6);
cout << 2;
}
o/p  * 12.53* * * 20.5 * * * * * 2

Note
There is no need to set fill and precision again and again while width flag
must be set again and again.

Formatting With Flags & Bit Fields

1> setf  long self (log-setbits, long – field)

Flag-value (1st argument) Bit field (2nd Arguments Description


Ios : : left ios : : adjust field justifies the output on
left side.
Ios : : right ios : : adjeist field justifies the output in
sight align mennes.
Ios : : internal ios : : adjust field passing accurs between
the sign or base indicator
& the value when the
value fails to fill the
entire width
ios : : dec ios : : base field display the data in decimal
conversion
ios : : oct “ display the data in actor
ios : : hax “ display the data in hexadecimal
ios : : scientific ios : : float field user exponential floating
notation
ios : : fixed “ user normal floating notation

Example :-

void main ( )
{
cout.self (ios : ; left, ios : : adjust field);
cout.fill (‘*’);
cout. precision (2);
cout.width (6);
cout << 12.53;
cout.width (6);
cout << 20.5;
cout.witdth (6);
cout <<2;
}
12.53 * 20.5 * * 2 * * * * *

void main ( )
{
cout.self (ios : : internal | ios : : adjust field );
cout.field (‘*);
cout. precision (2);
cout. width (10);
cout << -420.53;
}
Output : - - * * * 4 2 0 . 5 3

Displaying Trailing Zeros & Plus Sign


Long self (long – setbits)
(i) ios : : show pint (for trailing zeros)
(ii) ios : : show pos (for plus sign)

void main ( )
{
cout.setf (ios : : show point);
cout.precision (2);
cout << 20.55 << end1; output
cout << 55.55 << end1; 20.55
cout << 20.40 << end1; 55.55
} 20.40

Example :-
void main ( )
{
cout.setf (ios : : showpoint);
cout.setf (ios : : show pos);
cout.setf (ios : : internal, ios : : adjust field);
cout.precison(3);
cout.width (10);
cout << 420.53;
}
Output 
+ * 4 2 0 . 5 3 0

Formatting Data Using Manipulators


Non Parameterised Manipulators

Manipulator Description

1. end1 terminates the line and transfers the cursor to next row.
2. dec set conversion base to 10.
3. bex set the conversion field to 16.
4. oct set the conversion field to 8
5. flush flushes the output screen

Example :-
1. WAP to read a number in decimal and display it in hxadecimal.

void main ( )
{
cout << “ enter number”;
cin a;
cin >> a;
cout << “ no is = “ << n << end;
cout << “ It’s hexadecimal value= “ << hex<<n;
cout. self (ios : : show base);
cout << a;
}
Output:- no is = 64
Its hexaslccimal value = 40 0x 40

Example :- void main ( )


{
int n;
cout << “enter number”;
cin >> nex>> n;
cout << “number= “ << n;
}

Parameterised Manipulators

Manipulator Description

1. setw (int) sets the field width


2. setprecision (int) sets number of digits to be displayed after decimal
pint
3. setfil (char) sets the character to be field
4. setbase (int) set the conversion base. Here possible value of int
are 8.10 and 16.
5. setiosflag (long) sets the format flag.
6. resetiosflag (long) resets the format flag.

Example :-
void main ( )
{
int n = 100;
cout << hex <<n << “ “ << dec <<n << end1;
float f = 122.3434;
cout << f << end1;
cout << setprecision (3);
cout << f << end1;
cout << setiosflag (ios : : internal } ios : : show base);
cout << hex << n << end1;
cout << setiosfloag (ios : : scientifie) << f << end1;
}

Output:- 64 100
122.34339 9
122. 343
0x0064
1. 2 2 3 c + 0. 2

You might also like