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

Unit 4

The document discusses files and streams in C++. It defines streams as sequences of characters that can represent various data types. Files are used for permanent secondary storage and various file operations like opening, writing, reading and closing files are described. The key classes for file handling like fstream, ifstream and ofstream are explained along with examples of opening, writing to and reading from files in C++. Different file opening modes are also outlined.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Unit 4

The document discusses files and streams in C++. It defines streams as sequences of characters that can represent various data types. Files are used for permanent secondary storage and various file operations like opening, writing, reading and closing files are described. The key classes for file handling like fstream, ifstream and ofstream are explained along with examples of opening, writing to and reading from files in C++. Different file opening modes are also outlined.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

Bhujbal Knowledge City

MET Institute of Engineering

Object Oriented Programming[210243]


SE Computer Engineering
UNIT-IV
Files and Streams
By
Ms. Vaishali Khandave
Assistant Professor
Computer Engineering

02/11/2020 1
FILES AND STREAMS
Streams
 Streams are nothing but sequence of
characters.
 Characters may be normal or wild characters.
 Stream work with all built in data type.
 A stream is serial interface to storage, buffer
files, or any other storage medium.
 We can overload stream by overloading
<<(insertion) operator.

02/11/2020 2
Continued…
 iostream is nothing but standard input output stream library.
 It provides input output functionality using stream.
 Stream is abstraction which represent device on which input
and output operation are performed.
 To operate with stream c++ provides iostream library.
 It is mainly declared in header file<iostream>.
 It is derived from istream and ostream classes which is also
subclass of ios class.
 istream for input purpose whereas ostream for output purpose.

 For the file handling we have ifstream for input purpose and
ofstream for output purpose.
 It acts as both source and destination. In case of input, stream
acts as source where as in case of output it acts as destination.

02/11/2020 3
Continued…

Source which provides input to the program is


known as input stream. Keyboard, file, device
are example of input stream.
Destination stream is one where program can
send the output monitor, printer, file are
example of output stream.
Program extracts sequence of byte from the
input stream. Program adds sequence of byte to
output stream.

02/11/2020 4
Stream Classes
ios

istream ostream

iostream

ifstream ofstream

fstream
02/11/2020 5
Continued…
ios is base of all classes.
istream is used for input purpose.
ostream is used for output purpose.
iostream is used for both input and output.
ifstream is used for input from file.
ofstream is used for output to file.
fstream is used for both Input file and output with file.

Different object in iostream classes is as follows:


1.cin: standard input stream object, it is object of istream class. cin is actually
object and not function or anything else.
2.cout: standard output stream object.it is object of ostream class. cout is
object and not function.
3.cerr: standard output stream for error.

02/11/2020 6
Continued…
Iostream class also contains different manipulators some of the manipulators
are as follows:
Manipulators Meaning
Boolalpha Alphanumerical bool values
Dec Use decimal base
Endl New line
Ends Insert null
Fixed Use fixed point notation
Flush Flush stream buffer
Left Print output to left
Right Print output to right
Setfill Set fill character
Setw Set filled width
Ws Extract whitespaces
02/11/2020 7
Files
Files are part of secondary storage devices. It means once we store the data on these
devices, it will be permanently stored in it. Data storage with secondary storage devices
is possible using file concept. Example of secondary storage devices are hard disk, pen
drive, floppy, etc. We can read or write data in the file whenever required. C++
provides very user friendly list of functions to manipulate the files.

Different file operation are as follows:


 Create file
 Write to file
 Modify file
 Open file
 Close file
 Truncate file
 Read from file
 Append contents file

There are many more functions available to manipulate the information in the file.
Program can store the information in the file or read the data from file. Files can be
character or binary files.

02/11/2020 8
Opening File
 Whenever we need to read or write data in file, we
need to open the file.
 For file creation and file opening same function is
used.
 For opening file we need to decide where to store the
file and what name to give to identify the file.
 ofstream class is used to open the file. We need to
create object of ofstream class to open the file. After
creating object, it will open the file. If file is not
existing in the system, then new file will be created.
If file is existing in the file system, then file will be
truncated
02/11/2020 9
Continued…
Example:
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ofstream fout(Home:\\Test.txt);
return 0;
}

02/11/2020 10
File Closing Operation
Whenever we open the file we need to close it. It is possible
by close() function.

Example:
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ofstream fout(Home:\\Test.txt);
fout.close();
return 0;
}
02/11/2020 11
Writing data to file
For writing data to file we need to create or
open file first
If file is existing then existing file will be
truncated
We can write data to file using << put operator
with cout statement

02/11/2020 12
Writing data to file
#include<iostream>
#include<fstream>

using namespace std;

int main()
{
int roll;
char name[10];
float marks;

cout<<"\nFile opening Operation";


ofstream fout("Home:\\example.txt");

cout<<"\nEnter roll number:";


cin>>roll; //get input from user
fout<<roll<<"\n"; //write roll no in file

cout<<"\nEnter Name:";
cin>>name;
fout<<name<<"\n";

cout<<"Enter the marks:";


cin>>marks;
fout<<marks<<"\n";

fout.close();
return 0;
}

02/11/2020 13
Reading data from file
To read data from file we use object of
ifstream and >> operator
It is more like cin and >>

02/11/2020 14
Reading data from file
#include<iostream>
#include<fstream>
//now read data in temporary variable
using namespace std; ifstream fin("Home:\\example.txt");
fin>>roll;
int main() fin>>name;
{ fin>>marks;
int roll;
char name[10]; //Now print data
float marks; cout<<"\nRoll:"<< roll;
cout<r<"\nName:"<<name;
cout<<"\nFile reading operation"; cout<<"\nMarks:"<<marks;
return 0;
//first write data }
ofstream fout("Home:\\example.txt");

cout<<"\nEnter roll number:";


cin>>roll; //get input from user
fout<<roll<<"\n"; //write roll no in file

cout<<"\nEnter Name:";
cin>>name;
fout<<name<<"\n";

cout<<"Enter the marks:";


cin>>marks;
fout<<marks<<"\n";

fout.close();

02/11/2020 15
Reading data from file
File reading operation
Enter roll number:1

Enter Name:mahesh
Enter the marks:89

Roll:1
Name:mahesh
Marks:89

//we have first stored data in file,then read data from


file in temporary variable and then print using cout

02/11/2020 16
File Opening Mode
We can open file in different modes also
This mode should be used in open() function
They are applicable to open existing file or create
new file.
Syntax:
File_Objectname.open(“filename”,
“file_opening_mode”);

02/11/2020 17
Different File Opening Modes
File Opening Mode Meaning
are:
ios::app Useful to append content in existing file

ios::ate Open file and go to end of the file

ios::binary Open file in binary mode

ios::in Open file for only reading purpose

ios::nocreate Opening fails if file is not existing

ios::noreplace Opening fails if file is existing

ios::out Opening file for writing purpose

ios::trunc Delete all the contents of file

02/11/2020 18
Reading and Writing Class
Object from File
Unlike built in data types, we can write object
in file also.
Generally objects are written in binary mode.
Object is an important part in object oriented
programming. So will focus on writing or
reading object in file.
Read() and write() functions from ifstream and
ofstream classes are used to read or write object
in file.

02/11/2020 19
Continued..
Syntax:
File_objectname.read(address of class_object,
size of class_object);
File_objectname.write(address of class_object,
size of class_object);
Example
Suppose file object is f and class object to
read/write is obj1
f.read((char *)&obj1,sizeof(obj1));
f.write((char *)&obj1,sizeof(obj1));

02/11/2020 20
#include<iostream>
#include<fstream>
int main()
using namespace std; {
employee e;
class employee fstream file;
{
char name[20]; //file_obj_name.open("file_name","file_opening
int id; _mode");
float salary;
char dept[10]; file.open("sample",ios::in | ios::out);

public: //file opened in read and write mode


void accept()
{ e.accept();
cout<<"\nEnter the name:-"; file.write((char *)&e,sizeof(e));
cin>>name;
cout<<"\nEnter the id:-"; file.read((char *)&e,sizeof(e));
cin>>id; e.display();
cout<<"\nEnter the salary:-";
cin>>salary; return 0;
cout<<"\nEnter the dept:-"; }
cin>>dept;
}

void display()
{
cout<<"\nEmployee Information Is:";

cout<<"\n"<<name<<"\t"<<id<<"\t"<<salary<<"\t"<<dept<<"\n";
}
};

02/11/2020 21
student@thinkcenter:~$ ./a

Enter the name:-Ishaan

Enter the id:-1

Enter the salary:-50000

Enter the dept:-Computer

Employee Information Is:


Ishaan 1 50000 Computer

02/11/2020 22
Reading and Writing Multiple
Class Object from File
It is also possible to read or write multiple
objects in file.

02/11/2020 23
Reading and Writing Multiple Class
Object from File
#include<iostream>
#include<fstream>
int main()
using namespace std; {
employee e[3];
class employee fstream file;
{ int i;
char name[20]; //file_obj_name.open("file_name","file_opening
int id; _mode");
float salary; file.open("sample",ios::in | ios::out); //file
char dept[10]; opened in read and write mode
cout<<"\nEnter the information of 3 employee:";
public: for(i=0;i<3;i++)
void accept() {
{ e[i].accept();
cout<<"\nEnter the name:-"; file.write((char *)&e,sizeof(e));
cin>>name; }
cout<<"\nEnter the id:-";
cin>>id;
cout<<"\nEnter the salary:-"; cout<<"\nInformation of employee is:";
cin>>salary; for(i=0;i<3;i++)
cout<<"\nEnter the dept:-"; {
cin>>dept; file.read((char *)&e,sizeof(e));
} e[i].display();
}
void display()
{ return 0;
cout<<"\nEmployee Information Is:"; }
cout<<"\n"<<name<<"\t"<<id<<"\t"<<salary<<"\t"<<dept<<"\n";
}
};

02/11/2020 24
student@thinkcenter:~$ ./a
Continued….
Enter the information of 3 employee:
Enter the name:-a

Enter the id:-1

Enter the salary:-20000

Enter the dept:-comp

Enter the name:-b

Enter the id:-2

Enter the salary:-45000

Enter the dept:-it

Enter the name:-c

Enter the id:-3

Enter the salary:-50000

Enter the dept:-mech

Information of employee is:


Employee Information Is:
a 1 20000 comp

Employee Information Is:


b 2 45000 it

Employee Information Is:


c 3 50000 mech

02/11/2020 25
int main()
Write a c++ program that creates an output file,writes information to {
it,closes the file and open it again as an input file and read the sample obj;
information from the file. ofstream os;
os.open("Home:\\test.txt",ios::in|ios::out);
#include<iostream> if(!os)
#include<fstream> {
#include<cstdlib> cerr<<"Could not open output file\n";
exit(1);
using namespace std; }

cout<<"Writing the contents to the file...\n";


class sample obj.accept();
{ os.write((char *)&obj,sizeof(obj));
public: if(!os)
{
int roll; cerr<<"Could not write to file\n";
char name[20]; exit(1);
}
void accept()
{ os.close();
cout<<"\nEnter the roll no:";
cin>>roll; ifstream is;
cout<<"\nEnter the name:"; is.open("Home:\\test.txt",ios::in|ios::out);
cin>>name; if(!is)
} {
cerr<<"Could not open input file\n";
void display() exit(1);
{ }
cout<<roll<<"\n";
cout<<name<<"\n"; cout<<"Reading the contents from the file...\n";
} obj.display();
}; is.read((char *)&obj,sizeof(obj));
if(!is)
{
cerr<<"Could not read from file\n";
exit(1);
}
return 0;
02/11/2020 } 26
Continued….
student@ubuntu:~$ ./a
Writing the contents to the file...

Enter the roll no:1

Enter the name:Ishaan


Reading the contents from the file...
1
Ishaan

02/11/2020 27
Standard Errors Stream
•Cerr is object of ostream class
•It is attached to standard error device
•Standard error device is screen only
•Cerr is also used with the << put
operator

02/11/2020 28
#include<iostream>
Using namespace std;
Int main()
{
Char s[]=“Unable to read…”;
Cerr<<“Error Message:”<<s<<endl;
}
o/p
Error Message: Unable to read…

02/11/2020 29
File Pointers
Each file has two file pointers associated with
it.
1.Input pointer-useful for reading purpose
2.Output pointer-useful for writing purpose
We can read or write data on specified location
with file pointers.

02/11/2020 30
Continued..
When we open file in read mode, input pointer
is automatically located to start of the file.
When we open file in write mode, all contents
of files are deleted and file pointer is set to
beginning of the file.
When we wanted to open existing file for new
data addition then we need to open that file in
append mode and not in write mode. When file is
opened in append mode, file pointer is set to end
of the file. New contents can be added after the
current file pointer.
02/11/2020 31
Functions to manipulate file pointers
Function Meaning Example

seekg() Move input pointer fin.seekg(20);


to given position Move pointer to byte
20
seekp() Move output pointer fout.seekp(20);
to given position Move pointer to byte
20
tellg() Get the current int g=fin.tellg();
position of get
pointer
tellp() Get the current int p=fout.tellp();
position of put
pointer
02/11/2020 32
Continued..
Seek functions can also be used to offset in the file
It means we move in the file from beginning, end or
current position.
Syntax:
seekg(offset,ref_position);
Where,
offset-no.of byte to be traversed in the file
ref_position-reference point in the file like
start,end,current

02/11/2020 33
Reference position can be as follows
ios::beg //start of the file
ios::cur //current position in the file
ios::end //from the end of file

02/11/2020 34
Examples
Example Meaning
fout.seekg(10,ios::start Move to 10 bytes from start of the
) file
fout.seekg(20,ios::end) Move to 20 bytes from the end of
the file. It means, it goes backward
20 bytes from end of the file

fout.seekg(30,ios::cur) Moves 30 bytes from current file


pointer

02/11/2020 35
Types of file
Random Access File
With random access file, data can be accessed
from anywhere in the file
File pointer in the random access file can move
anywhere in the file
Different functions are provided by fstream
class to handle random access file.
Pointer movement within the file is done by
seekp() and seekg().

02/11/2020 36
Continued..
Sequential File
Data in sequential file should be accessed
sequentially.
Sequentially means one character should read
or write at a time
If we wanted to access even last character we
need to read all previous characters.
put() and get() can be used to read or write data
character by character
read() and write() functions are used to read or
write block of binary data.
02/11/2020 37
Error Handling in File I/O
Error handling is very important in file
handling.
There may be error present during file
handling
Some of the errors are file not found,could not
open file,could not read file,could not write in
the file,file does not exist.
Sometimes error could occurs due to invalid
file name

02/11/2020 38
Some Error Handling Functions
Function Meaning
eof() It returns true if end of file is
reached otherwise false
fail() It returns true when input or
output operation failed
bad() It returns true when invalid
operation is attempted to
perform
good() It returns true if no error
present
02/11/2020 39
Functions from ofstream class for writing
data to file
These functions are used to write(output)
contents to file. char ch1=‘R’;
char str[30]=“met”;
1. put(): The function is used to write one float f=25.3;
character at next position into the file. ofstream obj;
Syntax: put(char); obj.open(“a.txt”, “w”);
e.g. obj.put(ch1); //write letter R in the file

2. write(): The function is used to write a


block of data into a file. The data can be
primary variable, string, object etc.
Syntax:
write(char *data, int length);
e.g. obj.write(str, strlen(str));
//write string met to file

02/11/2020 40
Functions from ifstream class for reading data
from files
These functions are used to write(output) contents to file.
1. get(): The function is used to read next character from char ch1;
file. char str[30];
Syntax: get(char); ifstream obj;
e.g. obj.get(ch1); //read next character from file into ch obj.open(“a.txt”, “r”);

2. getline(): The function is used to read next string from


file.
Syntax: getline(char *str, int length);
e.g.obj.getline(str, 50); // reads next at most 49 characters
from file, into str as a string

3. read(): Reads data from file into the variable mentioned


in the function.
Syntax: read(char *data, int length);
e.g. obj.read(str, 50);
Reads maximum 50 characters from the file into char array
str.

02/11/2020 41
Sample Program1
Program to read the contents of input file and displays them. It also displays the total number of
characters in one line.

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
int count=0;
char c;
ifstream input;
cout<<"Reading the contents from file"<<endl;
input.open("sample.txt");
input.get(c);
while(c!='\n')
{
cout.put(c);
count++;
input.get(c);
}
cout<<"Number of characters in the file="<<count<<endl;
return 0;
}
02/11/2020 42
Sample Program2
Program to reads the content from file and displays each line. Finally display the total number of lines in the file
#include <iostream>
#include<fstream>
#include<string>
using namespace std;

int main()
{
int count=0;
char data[20];
ifstream input;
cout<<"Reading the contents fronm the file"<<endl;
input.open("Sample.txt");
input.getline(data,20,"\n");
int n=strlen(data);
while(input)
{
cout.write(data,n);
cout<<endl;
count++;
input.getline(data,20);
n=strlen(data);
}

cout<<"\n Number of lines in the file="<<count<<endl;


return 0;
}

02/11/2020 43
Command Line Arguments
 In C++ it is possible to accept command line arguments.
 Command line arguments are given after the name of a program in
command line operating systems like DOS or Linux, and are passed in to
the program from the operating system.
 It is possible to pass some values from the command line to your C
programs when they are executed. These values are called command line
arguments and many times they are important for your program especially
when you want to control your program from outside instead of hard
coding those values inside the code.
 To use command line arguments in program, you must first understand the
full declaration of the main function, which previously has accepted no
arguments.
 In fact, main can actually accept two arguments: one argument is number of
command line arguments and the other is a full list of all of the command
line arguments.

 Syntax:
int main(int argc, char *argv[])
02/11/2020 44
Command Line Arguments
 The integer, argc is the argument count. It is the number of
arguments passed into the program from the command line,
including the name of the program.
 The array of character pointers is the listing of all the
arguments. argv[0] is the name of the program or an empty
string if the name is not available. After that , every element
number is less than argc is a command line argument. You can
use each argv element just like a string or use argv as a two
dimensional array. argv[argc] is a null pointer.

02/11/2020 45
Command Line Arguments
#include <fstream>
#include <iostream>

using namespace std;

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


{
cout<<“\n Total Number of arguments=“<<argc;
for(int i=0; i<argc; i++)
cout<<“\nArgument”<<i<< argv[i];
return 0;
}

D:\>test 10 20 30 40 50
Total Number of arguments=6
Argument 0=test
Argument 1=10
Argument 2=20
Argument 3=30
Argument 4=40
Argument 5=50

02/11/2020 46
Command Line Arguments
#include <fstream>
#include <iostream>

using namespace std;

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


{
if ( argc != 2 ) // argc should be 2 for correct execution
// We print argv[0] assuming it is the program name
cout<<"usage: "<< argv[0] <<" <filename>\n";
else {
// We assume argv[1] is a filename to open
ifstream the_file ( argv[1] );
// Always check to see if file opening succeeded
if ( !the_file.is_open() )
cout<<"Could not open file\n";
else {
char x;
// the_file.get ( x ) returns false if the end of the file
// is reached or an error occurs
while ( the_file.get ( x ) )
cout<< x;
}
// the_file is closed implicitly here
}
}
02/11/2020 47
Sample Program
Write a program using open(), eof() and getline() member functions to open and read a file content line by line

#include <iostream>
#include<fstream>
using namespace std;

int main()
{
char filename[20]="demo2.txt";
char line[100];
ifstream fin;
fin.open(filename);
cout<<"\nFile data.....\n";
while(!fin.eof())
{
fin.getline(line, 100);
cout<<line<<endl;
}
fin.close();

return 0;
}

02/11/2020 48
Home Assignment
1. Write a program to create a file, read and write the
record into it. Every record contains Employee
name, id and salary. Store and retrieve at least 3
employee data.

2. Write a program to read the characters from file and


count them till end of file.

02/11/2020 49
END OF FOURTH UNIT

THANK YOU

02/11/2020 50

You might also like