Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

File Handling in C++

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 17

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);

Basic Operation On Text File In C++


File I/O is a five-step process:
1. Include the header file fstream in the program.
2. Declare file stream object.
3. Open the file with the file stream object.
4. Use the file stream object with >>, <<, or other input/output functions.
5. Close the files.
Following program shows how the steps might appear in program.
 

Program to write in a text file

#include <fstream>
using namespace std;
int main()
{
ofstream fout;
fout.open("out.txt");

char str[300] = "Time is a great teacher but


unfortunately it kills all its pupils. Berlioz";

//Write string to the file.


fout << str;

fout.close();
return 0;
}

Program to read from text file and display it

#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++;
}

cout << "Number of characters in file are " << count;


fin.close();
return 0;
}

Program to count number of words

#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;
}

Program to count number of lines

#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++;
}

cout << "Number of lines in file are " << 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;
}

Basic Operation On Binary File In C++


When data is stored in a file in the binary format, reading and writing
data is faster because no time is lost in converting the data from one format to another format. Such files are
called binary files. This following program explains how to create binary files and also how to read, write,
search, delete and modify data from binary files.
#include<iostream>
#include<fstream>
#include<cstdio>
using namespace std;

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();
}

/* function to search and display from binary file*/

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();
}

/* function to delete a record*/

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");
}

/* function to modify a record*/

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();

int pos = -1 * sizeof(obj);


file.seekp(pos, ios::cur);

file.write((char*)&obj, sizeof(obj));
}
}

file.close();
}

int main()
{
//Store 4 records in file
for(int i = 1; i <= 4; i++)
write_record();

//Display all records


cout << "\nList of records";
display();

//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.

Class template instantiations

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

The library and its hierarchy of classes is split in different files:

 <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:

1. Implicit Type Conversion Also known as ‘automatic type conversion’.


 Done by the compiler on its own, without any external trigger from the user.
 Generally takes place when in an expression more than one data type is present. In such condition type
conversion (type promotion) takes place to avoid lose of data.
 All the data types of the variables are upgraded to the data type of the variable with largest data type.

bool -> char -> short int -> int ->

unsigned int -> long -> unsigned ->

long long -> float -> double -> long double

 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).

Example of Type Implicit Conversion:

// An example of implicit conversion


  
#include <iostream>
using namespace std;
  
int main()
{
    int x = 10; // integer x
    char y = 'a'; // character c
  
    // y implicitly converted to int.
ASCII
    // value of 'a' is 97
    x = x + y;
  
    // x is implicitly converted to float
    float z = x + 1.0;
  
    cout << "x = " << x << endl
         << "y = " << y << endl
         << "z = " << z << endl;
  
    return 0;
}
Output:

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.

In C++, it can be done by two ways:

 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

// C++ program to demonstrate


// explicit type casting
  
#include <iostream>
using namespace std;
  
int main()
{
    double x = 1.2;
  
    // Explicit conversion from double to
int
    int sum = (int)x + 1;
  
    cout << "Sum = " << sum;
  
    return 0;
}
Output:

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:

Advantages of Type Conversion:

 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.

Below is the implementation of the above approach:


// C++ Program to concatenate two string

// using unary operator overloading


#include <iostream>
#include <string.h>
  
using namespace std;
  
// Class to implement operator overloading
// function for concatenating the strings
class AddString {
  
public:
    // Classes object of string
    char s1[25], s2[25];
  
    // Parametrized Constructor
    AddString(char str1[], char str2[])
    {
        // Initialize the string to class object
        strcpy(this->s1, str1);
        strcpy(this->s2, str2);
    }
  
    // Overload Operator+ to concat the string
    void operator+()
    {
        cout << "\nConcatenation: " << strcat(s1, s2);
    }
};
  
// Driver Code
int main()
{
    // Declaring two strings
    char str1[] = "Geeks";
    char str2[] = "ForGeeks";
  
    // Declaring and initializing the class
    // with above two strings
    AddString a1(str1, str2);
  
    // Call operator function
    +a1;
    return 0;
}
Approach 2: Using binary operator overloading.

 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.

Below is the implementation of the above approach:


/ C++ Program to concatenate two strings using

// binary operator overloading


#include <iostream>
#include <string.h>
  
using namespace std;
  
// Class to implement operator overloading function
// for concatenating the strings
class AddString {
  
public:
    // Class object of string
    char str[100];
  
    // No Parameter Constructor
    AddString() {}
  
    // Parametrized constructor to
    // initialize class Variable
    AddString(char str[])
    {
        strcpy(this->str, str);
    }
  
    // Overload Operator+ to concatenate the strings
    AddString operator+(AddString& S2)
    {
        // Object to return the copy
        // of concatenation
        AddString S3;
  
        // Use strcat() to concat two specified string
        strcat(this->str, S2.str);
  
        // Copy the string to string to be return
        strcpy(S3.str, this->str);
  
        // return the object
        return S3;
    }
};
  
// Driver Code
int main()
{
    // Declaring two strings
    char str1[] = "Geeks";
    char str2[] = "ForGeeks";
  
    // Declaring and initializing the class
    // with above two strings
    AddString a1(str1);
    AddString a2(str2);
    AddString a3;
  
    // Call the operator function
    a3 = a1 + a2;
    cout << "Concatenation: " << a3.str;
  
    return 0;
}
Stream Manipulators are functions specifically designed to be used in conjunction with the insertion (<<) and extraction
(>>) operators on stream objects, for example:

std::cout << std::setw(10);

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.

Following are some of the most widely used C++ manipulators:

endl

This manipulator has the same functionality as ‘\n’(newline character). But this also flushes the output stream.

Example

Live Demo

#include<iostream>

int main() {   std::cout << "Hello" << std::endl << "World!"; }

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

1.0 with showpoint: 1.00000

1.0 with noshowpoint: 1


setprecision

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() {

   const long double pi = 3.141592653589793239;

   std::cout << "default precision (6): " << pi << '\n'

             << "std::setprecision(10): " << std::setprecision(10) << pi << '\n';

Output

default precision (6): 3.14159

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() {

   std::cout << "no setw:" << 42 << '\n'

             << "setw(6):" << std::setw(6) << 42 << '\n'

             << "setw(6), several elements: " << 89 << std::setw(6) << 12 << 34 << '\n';

Output

no setw:42 setw(6):    42 setw(6), several elements: 89    1234

You might also like