Unit IV_C++ (File Handling)
Table of content
S. No. Topics
1. C++ Streams
2. C++ Stream Classes
3. I/O Classes
4. File and Stream Classes
5. Char I/O
6. String I/O
7. Object I/O
8. File Pointer
9. Exception Handling (try, catch and throw)
10. Template
1
Unit IV_C++ (File Handling)
C++ Streams -
C++ Stream Classes-
2
Unit IV_C++ (File Handling)
3
Unit IV_C++ (File Handling)
I/O Classes-
In C++, Input/Output (I/O) classes are part of the Standard Library, designed to manage input
and output operations such as reading from or writing to the console, files, or other devices. The
most commonly used I/O classes in C++ are defined in the <iostream.h> header, and they are
mainly used for handling the input and output of data in various formats.
I/O classes in C++:
1. istream (Input Stream)
Purpose: Used for reading input (e.g., from the keyboard or files).
Common objects: cin, ifstream
Methods:
o operator>> (extraction operator) to extract data from the stream.
o get(), getline(), etc., for more specific reading.
Example:
cin>> variable; // Extracts input from the standard input (keyboard).
2. ostream (Output Stream)
Purpose: Used for writing output (e.g., to the console or files).
Common objects: cout, ofstream
Methods:
o operator<< (insertion operator) to insert data into the stream.
o flush(), put(), etc., for more advanced operations.
Example:
cout<< "Hello, World!"; // Inserts output to the standard output (console).
4
Unit IV_C++ (File Handling)
3. fstream (File Stream)
Purpose: Used for file input and output.
Common objects: ifstream, ofstream, fstream
Methods:
o open(), close() for file handling.
o operator>> and operator<< for reading from and writing to files.
Example:
ofstreamoutFile("[Link]"); // Opens a file to write to.
outFile<< "Writing to file."; // Writes to the file.
[Link](); // Closes the file.
4. ios class
Purpose: Base class for both istream and ostream. It defines many settings and flags for
managing stream behaviors (e.g., setting formatting options).
Methods:
o setf(), unsetf(), precision(), etc., for manipulating stream formatting.
5
Unit IV_C++ (File Handling)
File and Stream Classes-
In C++, file and stream handling is done using various classes from the C++ Standard Library.
These classes are primarily found in the <fstream> header for file operations and the <iostream>
header for standard input/output streams.
1. File Streams :File operations in C++ are handled using the following classes from the
<fstream> header:
ifstream (Input File Stream): Used for reading files.
ofstream (Output File Stream): Used for writing to files.
fstream (File Stream): Can be used for both input and output operations on files.
Common Operations:
Opening a file: This is done by passing the file name and an optional mode (e.g., ios::in,
ios::out, etc.).
Reading from or writing to a file: Use stream operators (>> for reading and << for
writing).
Closing the file: Always close the file after operations to free resources.
Modes for File Streams:
When opening a file, you can specify modes to determine how the file is accessed:
ios::in: Open for reading (default for ifstream).
ios::out: Open for writing (default for ofstream).
ios::app: Append to the end of the file.
ios::ate: Move to the end of the file when opening.
ios::binary: Open in binary mode (for non-text files).
Basic Example:
Program for Opening File:
#include<iostream.h>
#include<fstream.h>
int main(){
fstream FileName;
[Link]("FileName", ios::out);
if (!FileName){
cout<<"Error while creating the file";
6
Unit IV_C++ (File Handling)
}
else{
cout<<"File created successfully";
[Link]();
}
return 0;
}
Output-
Program for Writing to File:
Program for Opening File with content:
#include<iostream.h>
#include<fstream.h>
#include<conio.h>
int main()
{
clrscr();
fstream FileName;
[Link]("[Link]", ios::out);
if (!FileName) {
cout<<" Error while creating the file ";
}
else {
cout<<"File created and data got written to file";
FileName<<"Our first file handling file";
[Link]();
}
getch();
return 0;
}
7
Unit IV_C++ (File Handling)
Output-
Program for Reading from File:
#include<iostream.h>
#include <fstream.h>
#include <conio.h>
int main()
{
clrscr();
fstream FileName;
[Link]("[Link]", ios::in);
if (!FileName) {
cout<<"File doesn’t exist.";
}
else {
char x;
while (1) {
FileName>>x;
if([Link]())
break;
cout<<x;
}
}
[Link]();
getch():
return 0;
}
Output-
8
Unit IV_C++ (File Handling)
Program for Writing and Reading:
#include <iostream.h>
#include <fstream.h>
#include <conio.h>
int main()
{
clrscr();
int age;
char name[20];
ofstream out("[Link]");
cout<<"Enter Name:"<<endl;
cin>>name;
out<<name <<endl;
cout<<"Enter Age:"<<endl;
cin>>age;
out<<age <<endl;
[Link](); // File is closed
ifstream in ("[Link]");
in>>name;
cout<<"name:"<<name<<endl;
in>>age;
cout<<"Age:"<<age;
[Link]();
return 0;
}
2. Stream Classes:
iostream: This class handles basic input and output operations via standard input and
output streams.
cin: Standard input stream (keyboard input).
cout: Standard output stream (console output).
cerr: Standard error stream (for error messages).
clog: Standard logging stream (for logging output)
9
Unit IV_C++ (File Handling)
Example of using fstream (both input and output):
#include <iostream.h>
#include <fstream.h>
#include <conio.h>
int main()
{
clrscr();
// Open a file for both input and output
fstream file("[Link]", ios::in | ios::out | ios::app);
if (file.is_open())
{
file<< "Adding a new line to the file." << endl;
[Link](0); // Move to the beginning of the file
char line[20];
while ( getline(file, line))
{
cout<< line << endl; // Print the contents of the file
}
[Link]();
}
else
{
cout<< "Unable to open the file." << endl;
}
getch()
return 0;
}
10
Unit IV_C++ (File Handling)
Char I/O -
In C++, character input/output (I/O) is typically handled through streams, specifically cin for
input and cout for output. These streams allow you to read and write characters as well as strings.
Here's an overview of how you can use char in C++ for I/O:
Reading and Writing a Single Character
Using cin and cout for characters:
You can use cin to read a single character and cout to output a character.
#include <iostream.h>
int main() {
char ch;
// Reading a single character
cout<< "Enter a character: ";
cin>>ch;
// Printing the character
cout<< "You entered: " <<ch<<endl;
return 0;
}
Output-
Enter a character: M
You entered: M
Handling char with [Link]() and [Link]()
Using [Link]() and [Link]() for reading/writing single characters:
The [Link]() function can read a single character, including spaces and newlines, while
[Link]() outputs a single character.
#include <iostream.h>
int main() {
char ch;
// Reading a single character with [Link]()
cout<< "Enter a character: ";
[Link](ch); // This can read spaces too
// Output the character using [Link]()
[Link](ch);
cout<<endl;
return 0;
}
11
Unit IV_C++ (File Handling)
Output-
Enter a character: j
j
12
Unit IV_C++ (File Handling)
String I/O-
In C++, String I/O refers to input and output operations involving strings (arrays of characters).
Strings in C++ can be handled using either C-style character arrays or the std::string class,
which is part of the C++ Standard Library.
1. C-style character arrays (C-strings)-C-strings are essentially arrays of characters ending with a
null character (\0).
Input- You can use functions like cin, get(), and getline() to read strings.
#include <iostream.h>
int main()
{
Char str[100];
// Usingcin to read a string (stops at first whitespace)
cout<< "Enter a string: ";
cin>>str;
cout<< "You entered: " <<str<<endl;
// Using getline() to read an entire line (including spaces)
cout<< "Enter a full line: ";
[Link](); // To clear the newline character from the input buffer
[Link](str, 100);
cout<< "You entered: " <<str<<endl;
return 0;
}
Output
Enter a string: pawan
You entered: pawan
Enter a full line: my name is pawan
You entered: my name is pawan
2. Formatted Input/output- For formatted input and output, C++ streams (cin, cout) work
similarly for both C-style and C++ strings.
#include<iostream>
#include<string>
int main()
{
string name;
13
Unit IV_C++ (File Handling)
cout<<"Enter your name: ";
getline(cin, name); // Get entire line including spaces
cout<<"Hello, "<< name <<"!"<<endl;
return0;
}
Output- Enter your name: pawan
pawan
14
Unit IV_C++ (File Handling)
Object I/O-
In C++, Object I/O refers to the process of reading and writing objects to and from storage (such
as files or streams).
C++ supports features for writing to and reading from the disk files objects directly.
The binary input and output functions read() and write() are designed to do exactly this
job.
These functions handle the entire structure of an object as a single unit, using the
computer’s internal representation of data.
For instance, the function write() copies a class object from the memory byte by byte
with no conversion.
Only data members are written to the disk file and the member functions are not.
The length of the object is obtained by sizeof operator.
Reading and Writing a Class Object-
#include<iostream.h>
#include<fstream.h>
#include<iomanip.h>
class Inventory
{
clrscr();
char name[20];
int code;
float cost;
public:
void readdata();
void show();
};
void Inventory::readdata()
{
cout<<"Enter Name: ";
cin>>name;
15
Unit IV_C++ (File Handling)
cout<<"Enter Code: ";
cin>>code;
cout<<"Enter Cost: ";
cin>>cost;
}
void Inventory::show()
{
cout<<setiosflags(ios::left)<<setw(10)<<name
<<setiosflags(ios::right)<<setw(10)<<code
<<setprecision(2)<<setw(10)<<cost<<endl;
}
void main()
{
Inventory item[3];
fstream file;
[Link]("[Link]",ios::in |ios::out);
cout<<"Enter Details of Items\n";
for(int i=0;i<3;i++)
{
item[i].readdata();
[Link]((char *) &item[i], sizeof(item[i]));
}
[Link](0);
cout<<"\n\nOutput\n\n";
for(i=0;i<3;i++)
{
[Link]((char *) &item[i], sizeof(item[i]));
item[i].show();
}
[Link]();
}
16
Unit IV_C++ (File Handling)
Output:
Explanation-
[Link]():
This is a function (likely from a file I/O library) that writes a block of data to a file.
(char *) & height:
&height gets the memory address of the height variable.
(char *) casts this memory address to a "pointer to char."
This is necessary because [Link]() typically expects a raw byte pointer as input. It
treats the data as a sequence of bytes without knowing the original data type.
sizeof(height):
This determines the size, in bytes, of the height variable. This is crucial for telling [Link]()
how many bytes to write from the memory location.
17
Unit IV_C++ (File Handling)
Opening and Closing file-
#include<iostream.h>
#include<fstream.h>
void main()
{
ofstream outf("Item");
char name[30];
float cost;
cout<<"Enter the Item Name: ";
cin>>name;
outf<<name<<"\n";
cout<<"Enter the Item Cost: ";
cin>>cost;
outf<<cost<<"\n";
[Link]();
ifstream inf("Item");
inf>>name;
inf>>cost;
cout<<"\n Item Name:"<<name<<"\n";
cout<<"Item cost:"<<cost<<"\n";
[Link]();
}
Output :
18
Unit IV_C++ (File Handling)
File Pointer-
All I/O streams objects have, at least, one internal stream pointer: ifstream, like istream, has a
pointer known as the get pointer that points to the element to be read in the next input operation.
ofstream, like ostream, has a pointer known as the put pointer that points to the location where
the next element has to be written.
Finally, fstream, inherits both, the get and the put pointers, from iostream (which is itself derived
from both istream and ostream).
File Manipulators-
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.
#include<iostream.h>
#include<fstream.h>
#include<string.h>
void main()
{
fstream file;
char name[30];
int i;
cout<<"Enter Name: ";
cin>>name;
int l=strlen(name);
[Link]("demo",ios::in | ios::out);
for(i=0;i<l;i++)
{
[Link](name[i]);
}
[Link](1);
char c;
while(file)
{
[Link](c);
cout<<c;
19
Unit IV_C++ (File Handling)
}
[Link]();
}
Output:
Write () and read () function:
The function write() and read() handles the data in binary form. This means that the values stored in the
disk file in the same format in which they stored in the internal memory.
An int takes two bytes to store its value in the binary form, irrespective of its size.
The binary format is more accurate for storing the numbers in the exact internal representation.
The binary format is much faster to saving the data to.
#include<iostream.h>
#include<fstream.h>
#include<iomanip.h>
#include<conio.h>
void main()
{
clrscr();
float height[5]={176,182,167.89,177.9,160.24};
ofstream ofile;
int i;
[Link]("data");
[Link]((char *) &height, sizeof(height));
[Link]();
ifstream infile;
[Link]("data");
20
Unit IV_C++ (File Handling)
[Link]((char *) &height, sizeof(height));
for(i=0;i<5;i++)
{
[Link](ios::showpoint);
cout<<setw(10)<<setprecision(2)<<height[i]<<endl;
}
[Link]();
}
Output:
21
Unit IV_C++ (File Handling)
Exception Handling-
22
Unit IV_C++ (File Handling)
// program to divide two numbers
// throws an exception when the divisor is 0
#include <iostream.h>
int main()
{
double numerator, denominator, divide;
cout << "Enter numerator: ";
cin >> numerator;
cout << "Enter denominator: ";
cin >> denominator;
try
{
// throw an exception if denominator is 0
if (denominator == 0)
throw 0;
// not executed if denominator is 0
divide = numerator / denominator;
cout << numerator << " / " << denominator << " = " << divide << endl;
}
catch (int num_exception)
{
cout << "Error: Cannot divide by " << num_exception << endl;
}
return 0;
}
23
Unit IV_C++ (File Handling)
Output:
Template-
Templates in C++ are a feature that enables generic programming by allowing functions and
classes to operate with different data types without the need to rewrite the code for each
type. Templates are blueprints for creating functions or classes. The actual type to be used is
specified later when the template is instantiated.
C++ template is also known as generic functions or classes which is a very powerful feature
in C++.
A keyword “template” in c++ is used for the template’s syntax and angled bracket in a
parameter (t), which defines the data type variable.
Types of Templates in C++-
Function template
Class templates
1. Function template - A function template in c++ is a single function template that works
with multiple data types simultaneously, but a standard function works only with one set of
data types.
C++ Function Template Syntax-
24
Unit IV_C++ (File Handling)
template<class type>ret-type func-name(parameter list)
{
//body of the function
}
#include <iostream.h>
#include <conio.h>
template <class T>
T add(T a, T b)
{
return a + b;
}
int main()
{
clrscr();
cout << "Integer addition: " << add(5, 3) << endl;
cout << "Double addition: " << add(5.5, 3.2) << endl;
getch();
return 0;
}
Output :
25
Unit IV_C++ (File Handling)
2. Class templates -
Class templates like function templates, are useful when a class defines something that is
independent of the data type.
#include <iostream.h>
#include <conio.h>
template <class Temp>
class Calculator
{
private:
Temp n1, n2;
public:
Calculator(Temp num1, Temp num2)
{
n1 = num1;
n2 = num2;
}
void show()
{
cout << "Addition is: " << n1 << "+" << n2 << "=" << addition() << endl;
}
Temp addition()
{
return (n1 + n2);
}
};
int main()
{
clrscr();
Calculator<int> Calc1(25, 12);
cout << "Integer results for 25 and 12:" << endl;
[Link]();
getch();
return 0;
}
Output :
26