Unit 4
Unit 4
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…
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.
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.
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>
int main()
{
int roll;
char name[10];
float marks;
cout<<"\nEnter Name:";
cin>>name;
fout<<name<<"\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 Name:";
cin>>name;
fout<<name<<"\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
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
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);
void display()
{
cout<<"\nEmployee Information Is:";
cout<<"\n"<<name<<"\t"<<id<<"\t"<<salary<<"\t"<<dept<<"\n";
}
};
02/11/2020 21
student@thinkcenter:~$ ./a
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
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; }
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
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
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
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”);
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);
}
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>
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>
#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.
02/11/2020 49
END OF FOURTH UNIT
THANK YOU
02/11/2020 50