File Handling in C++
File Handling in C++
File Handling in C++
File. The information / data stored under a specific name on a storage device, is called a file.
Stream. It refers to a sequence of bytes.
Text file. It is a file that stores information in ASCII characters. In text files, each line of text is terminated with
a special character known as EOL (End of Line) character or delimiter character. When this EOL character is
read or written, certain internal translations take place.
Binary file. It is a file that contains information in the same format as it is held in memory. In binary files, no
delimiters are used for a line and no translations occur here.
Classes for file stream operation
ofstream: Stream class to write on files
ifstream: Stream class to read from files
fstream: Stream class to both read and write from/to files.
Opening a file
OPENING FILE USING CONSTRUCTOR
ofstream outFile("sample.txt"); //output only
ifstream inFile(“sample.txt”); //input only
OPENING FILE USING open()
Stream-object.open(“filename”, mode)
ofstream outFile;
outFile.open("sample.txt");
ifstream inFile;
inFile.open("sample.txt");
File mode parameter Meaning
ios::app Append to end of file
ios::ate go to end of file on opening
ios::binary file open in binary mode
ios::in open file for reading only
ios::out open file for writing only
ios::nocreate open fails if the file does not exist
ios::noreplace open fails if the file already exist
ios::trunc delete the contents of the file if it exist
All these flags can be combined using the bitwise operator OR (|). For example, if we want to open the file
example.bin in binary mode to add data we could do it by the following call to member function open():
fstream file;
file.open ("example.bin", ios::out | ios::app | ios::binary);
Closing File
outFile.close();
inFile.close();
INPUT AND OUTPUT OPERATION
put() and get() function
the function put() writes a single character to the associated stream. Similarly, the function get() reads a single
character form the associated stream.
example :
file.get(ch);
file.put(ch);
write() and read() function
write() and read() functions write and read blocks of binary data.
example:
file.read((char *)&obj, sizeof(obj));
file.write((char *)&obj, sizeof(obj));
ERROR HANDLING FUNCTION
FUNCTI
RETURN VALUE AND MEANING
ON
returns true (non zero) if end of file is encountered while reading;
eof()
otherwise return false(zero)
fail() return true when an input or output operation has failed
returns true if an invalid operation is attempted or any unrecoverable error
bad()
has occurred.
good() returns true if no error has occurred.
File Pointers And Their Manipulation
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).
These internal stream pointers that point to the reading or writing locations within a stream can be manipulated
using the following member functions:
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
The other prototype for these functions is:
seekg(offset, refposition );
seekp(offset, refposition );
The parameter offset represents the number of bytes the file pointer is to be moved from the location specified
by the parameter refposition. The refposition takes one of the following three constants defined in the ios class.
ios::beg start of the file
ios::cur current position of the pointer
ios::end end of the file
example:
file.seekg(-10, ios::cur);
#include <fstream>
using namespace std;
int main()
{
ofstream fout;
fout.open("out.txt");
fout.close();
return 0;
}
#include<fstream>
#include<iostream>
using namespace std;
int main()
{
ifstream fin;
fin.open("out.txt");
char ch;
while(!fin.eof())
{
fin.get(ch);
cout << ch;
}
fin.close();
return 0;
}
Program to count number of characters.
#include<fstream>
#include<iostream>
using namespace std;
int main()
{
ifstream fin;
fin.open("out.txt");
int count = 0;
char ch;
while(!fin.eof())
{
fin.get(ch);
count++;
}
#include<fstream>
#include<iostream>
using namespace std;
int main()
{
ifstream fin;
fin.open("out.txt");
int count = 0;
char word[30];
while(!fin.eof())
{
fin >> word;
count++;
}
cout << "Number of words in file are " << count;
fin.close();
return 0;
}
#include<fstream>
#include<iostream>
using namespace std;
int main()
{
ifstream fin;
fin.open("out.txt");
int count = 0;
char str[80];
while(!fin.eof())
{
fin.getline(str,80);
count++;
}
fin.close();
return 0;
}
Program to copy contents of file to another file.
#include<fstream>
using namespace std;
int main()
{
ifstream fin;
fin.open("out.txt");
ofstream fout;
fout.open("sample.txt");
char ch;
while(!fin.eof())
{
fin.get(ch);
fout << ch;
}
fin.close();
fout.close();
return 0;
}
class Student
{
int admno;
char name[50];
public:
void setData()
{
cout << "\nEnter admission no. ";
cin >> admno;
cout << "Enter name of student ";
cin.getline(name,50);
}
void showData()
{
cout << "\nAdmission no. : " << admno;
cout << "\nStudent Name : " << name;
}
int retAdmno()
{
return admno;
}
};
/*
* function to write in a binary file.
*/
void write_record()
{
ofstream outFile;
outFile.open("student.dat", ios::binary | ios::app);
Student obj;
obj.setData();
outFile.write((char*)&obj, sizeof(obj));
outFile.close();
}
/* function to display records of file*/
void display()
{
ifstream inFile;
inFile.open("student.dat", ios::binary);
Student obj;
while(inFile.read((char*)&obj, sizeof(obj)))
{
obj.showData();
}
inFile.close();
}
void search(int n)
{
ifstream inFile;
inFile.open("student.dat", ios::binary);
Student obj;
while(inFile.read((char*)&obj, sizeof(obj)))
{
if(obj.retAdmno() == n)
{
obj.showData();
}
}
inFile.close();
}
void delete_record(int n)
{
Student obj;
ifstream inFile;
inFile.open("student.dat", ios::binary);
ofstream outFile;
outFile.open("temp.dat", ios::out | ios::binary);
while(inFile.read((char*)&obj, sizeof(obj)))
{
if(obj.retAdmno() != n)
{
outFile.write((char*)&obj, sizeof(obj));
}
}
inFile.close();
outFile.close();
remove("student.dat");
rename("temp.dat", "student.dat");
}
void modify_record(int n)
{
fstream file;
file.open("student.dat",ios::in | ios::out);
Student obj;
while(file.read((char*)&obj, sizeof(obj)))
{
if(obj.retAdmno() == n)
{
cout << "\nEnter the new details of student";
obj.setData();
file.write((char*)&obj, sizeof(obj));
}
}
file.close();
}
int main()
{
//Store 4 records in file
for(int i = 1; i <= 4; i++)
write_record();
//Search record
cout << "\nSearch result";
search(100);
//Delete record
delete_record(100);
cout << "\nRecord Deleted";
//Modify record
cout << "\nModify Record 101 ";
modify_record(101);
return 0;
}
The iostream library is an object-oriented library that provides input and output functionality using streams.
A stream is an abstraction that represents a device on which input and ouput operations are performed. A stream can
basically be represented as a source or destination of characters of indefinite length.
Streams are generally associated to a physical source or destination of characters, like a disk file, the keyboard, or the
console, so the characters gotten or written to/from our abstraction called stream are physically input/output to the
physical device. For example, file streams are C++ objects to manipulate and interact with files; Once a file stream is
used to open a file, any input or output operation performed on that stream is physically reflected in the file.
To operate with streams, C++ provides the standard iostream library, which contains the following elements:
Basic class templates
The base of the iostream library is the hierarchy of class templates. The class templates provide most of the functionality
of the library in a type-independent fashion.
This is a set of class templates, each one having two template parameters: the char type (charT) parameter, that
determines the type of elements that are going to be manipulated and the traits parameter, that provides additional
characteristics specific for a particular type of elements.
The class templates in this class hierarchy have the same name as their char-type instantiations but with the prefix
basic_. For example, the class template which istream is instantiated from is called basic_istream, the one
from which fstream is is called basic_fstream, and so on... The only exception is ios_base, which is by itself
type-independent, and therefore is not based on a template, but is a regular class.
The library incorporates two standard sets of instantiations of the entire iostream class template hierarchy: one is
narrow-oriented, to manipulate elements of type char and another one, wide-oriented, to manipulate elements of
type wchar_t.
The narrow-oriented (char type) instantiation is probably the better known part of the iostream library. Classes like
ios, istream and ofstream are narrow-oriented. The diagram on top of this page shows the names and
relationships of narrow-oriented classes.
The classes of the wide-oriented (wchar_t) instatiation follow the same naming conventions as the narrow-oriented
instantiation but with the name of each class and object prefixed with a w character, forming wios, wistream and
wofstream, as an example.
Standard objects
As part of the iostream library, the header file <iostream> declares certain objects that are used to perform input and
output operations on the standard input and output.
They are divided in two sets: narrow-oriented objects, which are the popular cin, cout, cerr and clog and their
wide-oriented counterparts, declared as wcin, wcout, wcerr and wclog.
Types
The iostream classes barely use fundamental types on their member's prototypes. They generally use defined types that
depend on the traits used in their instantiation. For the default char and wchar_t instantiations, types streampos,
streamoff and streamsize are used to represent positions, offsets and sizes, respectively.
Manipulators
Manipulators are global functions designed to be used together with insertion (<<) and extraction (>>) operators
performed on iostream stream objects. They generally modify properties and formatting settings of the streams.
endl, hex and scientific are some examples of manipulators.
Organization
<ios>, <istream>, <ostream>, <streambuf> and <iosfwd> aren't usually included directly in most C+
+ programs. They describe the base classes of the hierarchy and are automatically included by other header files
of the library that contain derived classes.
<iostream> declares the objects used to communicate through the standard input and output (including cin
and cout).
<fstream> defines the file stream classes (like the template basic_ifstream or the class ofstream) as
well as the internal buffer objects used with these (basic_filebuf). These classes are used to manipulate
files using streams.
<sstream>: The classes defined in this file are used to manipulate string objects as if they were streams.
<iomanip> declares some standard manipulators with parameters to be used with extraction and insertion
operators to modify internal flags and formatting options.
Compatibility notes
The names, prototypes and examples included in this reference for the iostream classes mostly describe and use the
char instantiations of the class templates instead of the templates themselves, even though these classes are only one
of their possible instantiations. We believe this provides a better readability and is arguably as easy to obtain the names
and prototypes of the basic template from the char instantiation as the opposite.
A type cast is basically a conversion from one type to another. There are two types of type conversion:
It is possible for implicit conversions to lose information, signs can be lost (when signed is implicitly
converted to unsigned), and overflow can occur (when long long is implicitly converted to float).
x = 107
y=a
z = 108
2. Explicit Type Conversion: This process is also called type casting and it is user-defined. Here the user can
typecast the result to make it of a particular data type.
Converting by assignment: This is done by explicitly defining the required type in front of the expression
in parenthesis. This can be also considered as forceful casting.
Syntax:
(type) expression
where type indicates the data type to which the final result is converted.
Example:
filter_none
edit
play_arrow
brightness_4
Sum = 2
Conversion using Cast operator: A Cast operator is an unary operator which forces one data type to be
converted into another data type.
C++ supports four types of casting:
1. Static Cast
2. Dynamic Cast
3. Const Cast
4. Reinterpret Cast
Example:
filter_none
edit
play_arrow
brightness_4
#include <iostream>
using namespace std;
int main()
{
float f = 3.5;
// using cast operator
int b =
static_cast<int>(f);
cout << b;
}
Output:
This is done to take advantage of certain features of type hierarchies or type representations.
It helps to compute expressions containing variables of different data types.
C++ Program to concatenate two strings using Operator Overloading
Approach 1: Using unary operator overloading.
To concatenate two strings using unary operator overloading. Declare a class with two string variables.
Create an instance of the class and call the Parametrized constructor of the class to initialize those two string
variables with the input strings from the main function.
Overload the unary operator to concatenate these two string variables for an instance of the class.
Finally, call the operator function and concatenate two class variables.
Declare a class with a string variable and an operator function ‘+’ that accepts an instance of the class and
concatenates it’s variable with the string variable of the current instance.
Create two instances of the class and initialize their class variables with the two input strings respectively.
Now, use the overloaded operator(+) function to concatenate the class variable of the two instances.
They are still regular functions and can also be called as any other function using a stream object as an argument, for
example:
boolalpha (cout);
Manipulators are used to changing formatting parameters on streams and to insert or extract certain special characters.
endl
This manipulator has the same functionality as ‘\n’(newline character). But this also flushes the output stream.
Example
Live Demo
#include<iostream>
Output
Hello
World!
showpoint/noshowpoint
This manipulator controls whether decimal point is always included in the floating-point representation.
Example
Live Demo
#include <iostream>
int main() {
std::cout << "1.0 with showpoint: " << std::showpoint << 1.0 << '\n'
<< "1.0 with noshowpoint: " << std::noshowpoint << 1.0 << '\n';
Output
This manipulator changes floating-point precision. When used in an expression out << setprecision(n) or in >>
setprecision(n), sets the precision parameter of the stream out or into exactly n.
Example
Live Demo
#include <iostream>
#include <iomanip>
int main() {
Output
std::setprecision(10): 3.141592654
setw
This manipulator changes the width of the next input/output field. When used in an expression out << setw(n) or in >>
setw(n), sets the width parameter of the stream out or in to exactly n.
Example
Live Demo
#include <iostream>
#include <iomanip>
int main() {
<< "setw(6), several elements: " << 89 << std::setw(6) << 12 << 34 << '\n';
Output