0% found this document useful (0 votes)
33 views

Unit 4 L11

Uploaded by

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

Unit 4 L11

Uploaded by

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

Unit 5 Files

OBJECT ORIENTED PROGRAMMING USING C++


Working with files and streams

 c++ streams,
 c++ stream classes,
 classes for file stream operations,
 opening & closing files,
 detection of end of file,
 more about open(): file modes,
 file pointer & manipulator,
 sequential input & output operation,
 updating a file: random access,
 command line arguments

OBJECT ORIENTED PROGRAMMING USING C++


OBJECT ORIENTED PROGRAMMING USING C++
#include <iostream>
using namespace std; Temporary
Storage
int main() RAM
{ 5aaa
int num;
cout<<"Enter number"<<endl;
cin>>num;
return 0;
}

OBJECT ORIENTED PROGRAMMING USING C++


Managing Output Stream/Input Stream
The sequence of bytes given as input to the executing
program and the sequence of bytes that comes as output from
the executing program are called stream. In other words,
streams are nothing but the flow of data in a sequence. Hard disk

File
Stream: flow of data
RAM
Output stream
vari
able Input stream File
Data from variable to file- output stream
Data from file to variable-input stream

We have predefine classes to manage all these things

OBJECT ORIENTED PROGRAMMING USING C++


C++ Stream Classes
The I/O system of C++ contains a set of classes
which define the file handling methods.

OBJECT ORIENTED PROGRAMMING USING C++


Classes for file stream

ios

istream ostream
>> <<
extraction
insertion
iostream

ifstream fstream ofstream

istream_withassign ostream_withassign
cin cout
OBJECT ORIENTED PROGRAMMING USING C++
1. ios/iostream
• ios stands for input output stream.
• This class is the base class for other classes in
this class hierarchy.
• This class contains the necessary facilities that
are used by all the other derived classes for
input and output operations.

OBJECT ORIENTED PROGRAMMING USING C++


2. istream
• istream stands for input stream.
• This class is derived from the class ‘ios’.
• This class handle input stream.
• The extraction operator(>>) is overloaded in
this class to handle input streams from files to
the program execution.
• This class declares input functions such as
get(), getline() and read().

OBJECT ORIENTED PROGRAMMING USING C++


3. ostream
• ostream stands for output stream.
• This class is derived from the class ‘ios’.
• This class handle output stream.
• The insertion operator(<<) is overloaded in
this class to handle output streams to files from
the program execution.
• This class declares output functions such as
put() and write().

OBJECT ORIENTED PROGRAMMING USING C++


4. streambuf:-
• This class contains a pointer which points to
the buffer which is used to manage the input
and output streams.
5. fstreambase:-
• This class provides operations common to the
file streams. Serves as a base for fstream,
ifstream and ofstream class.
• This class contains open() and close()
function.
OBJECT ORIENTED PROGRAMMING USING C++
6. ifstream:-
• This class provides input operations.
• It contains open() function with default input mode.
• Inherits the functions get(), getline(), read(), seekg()
and tellg() functions from the istream.
7. ofstream:-
• This class provides output operations.
• It contains open() function with default output mode.
• Inherits the functions put(), write(), seekp() and tellp()
functions from the ostream.

OBJECT ORIENTED PROGRAMMING USING C++


8. fstream:-
• This class provides support for simultaneous input
and output operations.
• Inherits all the functions from istream and ostream
classes through iostream.
9. filebuf:-
• Its purpose is to set the file buffers to read and write.
• We can also use file buffer member function to
determine the length of the file.
OBJECT ORIENTED PROGRAMMING USING C++
OBJECT ORIENTED PROGRAMMING USING C++
In C++, files are mainly deal with three classes
fstream, ifstream, ofstream.
ofstream: This Stream class indicates the output
file stream and is applied to create files for
writing information to files
ifstream: This Stream class indicates the input
file stream and is applied for reading
information from files
fstream: This Stream class can be used for both
read and write from/to files.
OBJECT ORIENTED PROGRAMMING USING C++
C++ provides us with the following
operations in File Handling:
• Creating a file: open()
• Reading data: read()
• Writing new data: write()
• Closing a file: close()

OBJECT ORIENTED PROGRAMMING USING C++


OBJECT ORIENTED PROGRAMMING USING C++
File Modes

ios::in Open for input operations.


ios::out Open for output operations.
ios::binary Open in binary mode.
Set the initial position at the end of the
file.
ios::ate
If this flag is not set, the initial position is
the beginning of the file.
All output operations are performed at
ios::app the end of the file, appending the content
to the current content of the file.

class default mode parameter

ofstream ios::out

ifstream ios::in

fstream ios::in | ios::out


OBJECT ORIENTED PROGRAMMING USING C++
Searches for the file and opens it in the read
ios::in mode only(if the file is found).

Searches for the file and opens it in the write mode. If the
file is found, its content is overwritten. If the file is not
ios::out found, a new file is created. Allows you to write to the
file.

Searches for the file and opens it in the append mode i.e.
ios::app this mode allows you to append new data to the end of a
file. If the file is not found, a new file is created.

OBJECT ORIENTED PROGRAMMING USING C++


Searches for the file and opens the file(if the file is found)
ios::binary in a binary mode to perform binary input/output file
operations.

Searches for the file, opens it and positions the pointer at


ios::ate the end of the file. This mode when used with ios::binary,
ios::in and ios::out modes, allows you to modify the
content of a file.

ios::trunc Searches for the file and opens it to truncate or deletes all
of its content(if the file is found).

OBJECT ORIENTED PROGRAMMING USING C++


ios::nocreate Searches for the file and if the file is not found,
a new file will not be created.

OBJECT ORIENTED PROGRAMMING USING C++


C++ provides us with the following
operations in File Handling:
• Creating a file: open()
• Reading data: read()
• Writing new data: write()
• Closing a file: close()

OBJECT ORIENTED PROGRAMMING USING C++


Opening Files using open()

• open() In case of creating new file:


– Using ofstream class
Syntax:
ofstream fout;
fout.open(“filename”)

• open() In case of reading file:


– Using ifstream class
Syntax:
ifstream fin;
fin.open(“filename”)
OBJECT ORIENTED PROGRAMMING USING C++
Opening Files using constructor
ofstream fout(“filename”);

ifstream infile(“salary”);

OBJECT ORIENTED PROGRAMMING USING C++


Closing Files
• close() In case of creating new file:
– Using ofstream class
Syntax:
ofstream fout;
fout.close()

• close() In case of reading file:


– Using ifstream class
Syntax:
ifstream fin;
fin.close()

OBJECT ORIENTED PROGRAMMING USING C++


Reading and Writing into Files

• Writing File: used ofstream class:


Syntax:
ofstream fout;
fout.open(“filename”);
fout<<“data”;
• Reading File: used ifstream class:
Syntax:
ifstream fin;
Ifstream.open(“filename”);
using get() or getline()
OBJECT ORIENTED PROGRAMMING USING C++
Reading Files: using get() function

The get() function is member of ifstream class. It is used to read


character form the file.
while(!fin.eof())
{
fin.get(ch);
cout<<ch;
}
will read all the characters one by one up to EOF(end-of-file)
reached.

OBJECT ORIENTED PROGRAMMING USING C++


Writing Files: using put() function

ofstream fout; // create output stream


char ch=‘a’;
int i;
fout.open("filename", ios::app) ;
/* write the characters to file using put() */
fout.put(ch);
fout.close();

OBJECT ORIENTED PROGRAMMING USING C++


Detecting End-of-File
 While reading data from a file, if the file contains multiple rows, it is
necessary to detect the end of file.
 This can be done using the eof() function of ios class.
 It returns 0 when there is data to be read and a non-zero value if
there is no data.
Syntax:
ifstream fin;
char ch;
Ifstream.open(“filename”);
while(!fin.eof())
{
fin.get(ch);
cout<<ch;
}

OBJECT ORIENTED PROGRAMMING USING C++


Check file is existing or not:
ifstream fin;
fin.open(“abc.txt”);
If(fin)
{
cout<<“File is existing”<<endl;
}
else{
cout<<“File is not existing”<<endl;

}
OBJECT ORIENTED PROGRAMMING USING C++
Reading Files: using getline()
How to process a file line by line in C++?

In C++, you may open a input stream on the file and use
the getline() function from the <string> to read content
line by line into a string and process them.
Ifstream fin;
fin.open("d://demo//file1.txt");
string str;
while(getline(fin,str))
{
cout<<str<<endl;
}
OBJECT ORIENTED PROGRAMMING USING C++
writing to a file

OBJECT ORIENTED PROGRAMMING USING C++


reading from a file

OBJECT ORIENTED PROGRAMMING USING C++


OBJECT ORIENTED PROGRAMMING USING C++
OBJECT ORIENTED PROGRAMMING USING C++
OBJECT ORIENTED PROGRAMMING USING C++
OBJECT ORIENTED PROGRAMMING USING C++
#include <fstream>
#include <iostream>
using namespace std;

int main()
{
string line;
ifstream ini_file("original.txt“);
ofstream out_file( "copy.txt“);
if (ini_file && out_file)
{
while (getline(ini_file, line))
{
out_file << line << "\n";
}
cout << "Copy Finished \n";
}
else {
// Something went wrong
printf("Cannot read File");
}
ini_file.close();
out_file.close();
return 0;
}

OBJECT ORIENTED PROGRAMMING USING C++


C++ File Manipulators
• The header file iomanip provides a set of functions called
manipulators which can be used to the manipulate the output
formats.
• The manipulators in C++ are special functions that can be
used with insertion (<<) and extraction (>>) operators to
manipulate or format the data in the desired way.
• Certain manipulators are used with << operator to display the
output in a particular format, whereas certain manipulators are
used with >> operator to input the data in the desired form.
• The manipulators are used to set field widths, set precision,
inserting a new line, skipping white space etc.

OBJECT ORIENTED PROGRAMMING USING C++


• In a single I/O statement, we can have more
than one manipulator, which can be chained as
shown

OBJECT ORIENTED PROGRAMMING USING C++


OBJECT ORIENTED PROGRAMMING USING C++
OBJECT ORIENTED PROGRAMMING USING C++
OBJECT ORIENTED PROGRAMMING USING C++
OBJECT ORIENTED PROGRAMMING USING C++
OBJECT ORIENTED PROGRAMMING USING C++
OBJECT ORIENTED PROGRAMMING USING C++
OBJECT ORIENTED PROGRAMMING USING C++
Steps:
1. Create a product class

Class

Data Members

Member
functions()

OBJECT ORIENTED PROGRAMMING USING C++


Steps:
2. Create a file and fill all product records.
3. Update your file, fill more records into file
3. Display output to the user screen with
product details.

OBJECT ORIENTED PROGRAMMING USING C++


Read/Write Class Objects from/to File in C++
The data transfer is usually done using '>>' and
<<' operators. But if you have a class with 4 data
members and want to write all 4 data members
from its object directly to a file or vice-versa.

OBJECT ORIENTED PROGRAMMING USING C++


To write object's data members in a file :
// Here file_obj is an object of ofstream
file_obj.write((char *) & class_obj, sizeof(class_obj));
To read file's data members into an object :
// Here file_obj is an object of ifstream
file_obj.read((char *) & class_obj, sizeof(class_obj));

OBJECT ORIENTED PROGRAMMING USING C++


#include <iostream>
#include<fstream>
using namespace std; A.
ofstream fout; File will create and hello
ifstream fin; will be written on file
B.
int main()
{
Compilation Error
fout.open("hello.txt", ios::in); C.
fout<<"hello"<<endl; Nothing will be happen
fout.close(); D.
return 0; None
}
OBJECT ORIENTED PROGRAMMING USING C++
File Pointers

OBJECT ORIENTED PROGRAMMING USING C++


Sequential and Random I/O

 C++ allows data to be read or written from a file in


sequential or random fashion.
 Reading data character by character or record by
record is called sequential access.
 Reading data in any order is known as random
access.
 The fstream class provides functions like get(), read()
for reading data and put(), write() for writing data to
a file.

OBJECT ORIENTED PROGRAMMING USING C++


OBJECT ORIENTED PROGRAMMING USING C++
OBJECT ORIENTED PROGRAMMING USING C++
• For example, if you have to modify a value in
record no 21, then using random access
techniques, you can place the file pointer at
the beginning of record 21 and then straight-
way process the record. If sequential access is
used, then you'll have to unnecessarily go
through first twenty records in order to reach
at record 21.
• In C++, random access techniques is achieved
by manipulating seekg(), seekp(), tellg() and
tellp() functions.
OBJECT ORIENTED PROGRAMMING USING C++
OBJECT ORIENTED PROGRAMMING USING C++
OBJECT ORIENTED PROGRAMMING USING C++
OBJECT ORIENTED PROGRAMMING USING C++
OBJECT ORIENTED PROGRAMMING USING C++
OBJECT ORIENTED PROGRAMMING USING C++
OBJECT ORIENTED PROGRAMMING USING C++
origin:
ios::beg start of the file
ios::cur current position of the pointer
ios::end end of the file
Ex:
fin.seekg(0, ios::beg);

OBJECT ORIENTED PROGRAMMING USING C++


fin.seekg(30, ios::beg); // go to byte no. 30 from beginning of
file linked with fin
fin.seekg(-2, ios::cur); // back up 2 bytes from the current
position of get pointer
fin.seekg(0, ios::end); // go to the end of the file
fin.seekg(-4, ios::end); // backup 4 bytes from the end of the
file

OBJECT ORIENTED PROGRAMMING USING C++


seekp() function allow us to move the output
pointer to specified location for writing purpose
within the file. The basic syntax for seekp()
function is :
fileObject.seekp(long_num, origin);
 fileObject: pointer to file
 long_num: no. of bytes in file we want to skip
 origin: where to begin

OBJECT ORIENTED PROGRAMMING USING C++


seekg() function allow us to move the Input
pointer to specified location for reading purpose
within the file. The basic syntax for seekg()
function is :
fileObject.seekg(long_num, origin);
 fileObject: pointer to file
 long_num: no. of bytes in file we want to skip
 origin: where to begin

OBJECT ORIENTED PROGRAMMING USING C++


The seekg() or seekp() then it moves the get_pointer or
put_pointer to an absolute position. Here is an example:

ifstream fin;
ofstream fout;
// file opening routine
fin.seekg(30); /*will move the get_pointer (in
ifstream) to byte number 30 in the file*/
fout.seekp(30); /* will move the put_pointer (in
ofstream) to byte number 30 in the file*/

OBJECT ORIENTED PROGRAMMING USING C++


seekg() moves get pointer(input) to a
specified location
seekp() moves put pointer (output) to a
specified location
tellg() gives the current position of the get
pointer
tellp() gives the current position of the put
pointer

OBJECT ORIENTED PROGRAMMING USING C++


Seekg()
#include <fstream>
#include <iostream>
using namespace std;
int main ()
{
fstream obj; Hello world
obj.open("test.txt", ios::in); world
int pos=6;
obj.seekg(pos);
while(!obj.eof())
{
char ch;
obj>>ch;
cout<<ch;
}
obj.close();
}

OBJECT ORIENTED PROGRAMMING USING C++


Seekp()
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
fstream obj; Hello World
obj.open ("test.txt", ios::out); Hello...And here the text changed
obj<<"Hello World";
int pos = 6;
obj.seekp(pos-1);
obj<<"...And here the text changed";
obj.close();
return 0;
}

OBJECT ORIENTED PROGRAMMING USING C++


tellp():-tells the put pointers location
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
fstream obj;
obj.open ("test.txt", ios::out);
obj<<"Hello World";
int pos;
pos = obj.tellp();
cout<<pos;
obj.close();
}

OBJECT ORIENTED PROGRAMMING USING C++


tellg(): tells the get pointers location
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
fstream obj;
obj.open ("test.txt", ios::in);
char ch;
int pos;
while(!obj.eof())
{
obj>>ch;
pos = obj.tellg();
cout<<pos<<"."<<ch<<"\n";
}
obj.close();
}

OBJECT ORIENTED PROGRAMMING USING C++


Setting the EOF flag off, to allow the access of
file again for reading:-
Ifstream fin;
fin.clear();

OBJECT ORIENTED PROGRAMMING USING C++


Which function is used to reposition the
file pointer?
a) moveg()
b) seekg()
c) changep()
d) go_p()

OBJECT ORIENTED PROGRAMMING USING C++


Which of the following is used to move the file
pointer to start of a file?
a) ios::beg
b) ios::start
c) ios::cur
d) ios::first

OBJECT ORIENTED PROGRAMMING USING C++


Command-line arguments
• Command-line arguments are given after the
name of the program in command-line shell of
Operating Systems.
• To pass command line arguments, we use
main() with two arguments :
– first argument is the total number of command line
arguments and
– second is list of command-line arguments.

OBJECT ORIENTED PROGRAMMING USING C++


Syntax:
int main(int argc, char *argv[ ])
{
return 0;
}
first parameter argc holds the count of command-line
arguments and the second parameter, an array of
character pointers holds the list of command-line
arguments.
first element in the array, i.e., argv[0] holds the filename. First
command-line parameter will be available in argv[1], second
parameter in argv[2] and so on.
OBJECT ORIENTED PROGRAMMING USING C++
• argv[0] holds the name of the program itself
• argv[1] is a pointer to the first command line
argument supplied, and *argv[n] is the last
argument.
• If no arguments are supplied, argc will be one,
and if you pass one argument then argc is set
at 2.

OBJECT ORIENTED PROGRAMMING USING C++


To execute the program, the program is called by command
line as,

ProgramName argument1

Here only one argument is passed. To pass multiple


arguments we can write it as,

ProgramName argu1 argu2 argu3.....

OBJECT ORIENTED PROGRAMMING USING C++


#include <iostream.h>
int main( int argc, char *argv[] )
{
if( argc == 2 ) {
cout<<"The argument supplied is “<< argv[1]);
}
else if( argc > 2 ) {
cout<<"Too many arguments supplied.”;
}
else {
cout<<"One argument expected.";
}
}

OBJECT ORIENTED PROGRAMMING USING C++


#include<stdio.h>
int main(int argc, char *argv[])
{
if(argc!=2){
printf("\nArgument not in correct format\n");
exit(1);
}

if(atoi(argv[1])%2==0)
printf("\nEVEN NUMBER\n");
else
printf("\nODD NUMBER\n");

return 0;
}

OBJECT ORIENTED PROGRAMMING USING C++


List.cpp
#include <iostream>
using namespace std;

int main(int argc, char** argv)


{
cout << "You have entered " << argc
<< " arguments:" << "\n";

for (int i = 0; i < argc; ++i)


cout << argv[i] << "\n";

return 0;
}

OBJECT ORIENTED PROGRAMMING USING C++


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

void main(int argc, char* argv[])


{
clrscr();
cout<<"\n Program name : \n"<<argv[0];
cout<<"1st arg :\n"<<argv[1];
cout<<"2nd arg :\n"<<argv[2];
cout<<"3rd arg :\n"<<argv[3];
cout<<"4th arg :\n"<<argv[4];
cout<<"5th arg :\n"<<argv[5];
getch();
}

OBJECT ORIENTED PROGRAMMING USING C++


Any Query?

Unit-4 End

OBJECT ORIENTED PROGRAMMING USING C++

You might also like