Friday, 21 June 2019

File Handling through C++ Classes

A stream is a name given to a flow of data at the lowest level. At the lowest level, data is just the binary data without any notion of data type. Different streams are used to represent the different kinds of data flow such as whether data is flowing into the memory or out of the memory.
Each stream is associated with a particular class,  that contains the member functions and definitions for dealing with that particular kind of data flow. For instance, the ifstream class represents the input disk files.
The stream that supplies data to the program is known as the input stream. It reads the data from the file and hands it over to the program. The stream that receives data from the program is known as output stream. It writes the received data to the file.
The file I/O system of C++ contains a set of classes that define the file handling methods. These classes, designed to manage the disk files, are declared in the header file named fstream.h. Therefore, we must include this file in a program that works with files. The classes defined inside the header file, fstream.h, derive from the classes under the header file iostream.h, the header file that manages console I/O operations.
Therefore, if you include the header file fstream.h in your file handling programs, you need not to include iostream.h header file as classes of fstream.h inherit from iostream.h only.
The function of these classes have been summarized in the following table :
Class                         .................................
Functions
filebuf                         
It sets the file buffers to read and write. It contains close() and open() member functions to it
fstreambase    
This is the base class for fstream, ifstream and ofstream classes. Therefore, it provides operations common to these file streams. It also contains the functions open() and close()
ifstream            

Being an input file stream class, it provides the input operations for file. It inherits the functions get(), getline(), read() and functions supporting random access ( seekg() and    tellg() ) from istream class defined inside the header file iostream.h
ofstream
Being an output file stream class, it provides the output operations. It inherits the functions put() and write() along with functions supporting random access ( seekp() and tellp() ) from ostream class defined inside the header file iostream.h
fstream
It is an input-output file stream class. It provides support for the simultaneous input and output operations. It inherits all the functions from istream and ostream classes through the iostream class defined inside the header file iostream.h

#include <iostream>
#include <conio.h>

#include <fstream>

using namespace std;

int   main()

{

    ofstream fout;

    string line;

     fout.open("sample.txt");

     fout << line << endl;

     fout.close();

    return 0;

}





#include <conio.h>
#include <fstream>
using namespace std;
int   main()
{
    ofstream fout;
    string line;
     fout.open("sample.txt");
     fout << line << endl;
     fout.close();
    return 0;
}

 

C++ File Streams Example

Here is a simple example program related to C++ file stream. This programs only ask to enter the file name and then to enter a line to store the line in this file.
/* C++ File Streams */
 
#include<conio.h>
#include<fstream.h>
#include<stdlib.h>
void main()
{
        char inform[80];
        char fname[20];
        char ch;
        clrscr();
 
        cout<<"Enter file name: ";
        cin.get(fname, 20);
        ofstream fout(fname, ios::out);
 
        if(!fout)
        {
               cout<<"Error in creating the file..!!\n";
               cout<<"Press any key to exit...\n";
               getch();
               exit(1);
        }
        cin.get(ch);
 
        cout<<"Enter a line to store in the file:\n";
        cin.get(inform, 80);
        fout<<inform<<"\n";
 
        cout<<"\nEntered informations successfully stored..!!\n";
        fout.close();
        cout<<"Press any key to exit...\n";
        getch();
}
Here is the sample run of the above C++ program:
Description: c++ file streams

 

 

TEXT and Binary Files:
Files are required to store any information permanently, for later use. The same holds for data files also.
The data files are the files that store data pertaining to a specific application, for later use. The data files can be stored in the following two ways :
  1. Text files
  2. Binary files
Text file
A text file stores the information in ASCII characters. In text files, each line of text is terminated or delimited with a special character named EOF known as End of Line character.
In text files, some internal translations take place when this EOF character is read or written.
Binary file
A binary file is just a file that contains information in the same format in which the information is held in memory.
In binary file, there is no delimiter for a line. Also no translations occur in binary file. As a result, binary files are faster and easier for a program to read and write than are text files. As long as the file doesn't need to be read by people or need to be ported to a different type of system, binary files are the best way to store program information.

Q: What is the difference between binary and text files?

A: All files can be categorized into one of two file formats — binary or text. The two file types may look the same on the surface, but they encode data differently. While both binary and text files contain data stored as a series of bits (binary values of 1s and 0s), the bits in text files represent characters, while the bits in binary files represent custom data.
While text files contain only textual data, binary files may contain both textual and custom binary data.

Binary Files

Binary files typically contain a sequence of bytes, or ordered groupings of eight bits. When creating a custom file format for a program, a developer arranges these bytes into a format that stores the necessary information for the application. Binary file formats may include multiple types of data in the same file, such as image, video, and audio data. This data can be interpreted by supporting programs, but will show up as garbled text in a text editor. Below is an example of a .PNG image file opened in an image viewer and a text editor.
Image ViewerText Editor
Flower - Image ViewerFlower - Text Editor
As you can see, the image viewer recognizes the binary data and displays the picture. When the image is opened in a text editor, the binary data is converted to unrecognizable text. However, you may notice that some of the text is readable. This is because the PNG format includes small sections for storing textual data. The text editor, while not designed to read this file format, still displays this text when the file is opened. Many other binary file types include sections of readable text as well. Therefore, it may be possible to find out some information about an unknown binary file type by opening it in a text editor.
Binary files often contain headers, which are bytes of data at the beginning of a file that identifies the file's contents. Headers often include the file type and other descriptive information. For example, in the image above, the "PNG" text indicates the file is a PNG image. If a file has invalid header information, software programs may not open the file or they may report that the file is corrupted.

Text Files

Text files are more restrictive than binary files since they can only contain textual data. However, unlike binary files, they are less likely to become corrupted. While a small error in a binary file may make it unreadable, a small error in a text file may simply show up once the file has been opened. This is one of reasons Microsoft switched to a compressed text-based XML format for the Office 2007 file types.
Text files may be saved in either a plain text (.TXT) format and rich text (.RTF) format. A typical plain text file contains several lines of text that are each followed by an End-of-Line (EOL) character. An End-of-File (EOF) marker is placed after the final character, which signals the end of the file. Rich text files use a similar file structure, but may also include text styles, such as bold and italics, as well as page formatting information. Both plain text and rich text files include a (character encoding| characterencoding) scheme that determines how the characters are interpreted and what characters can be displayed.
Since text files use a simple, standard format, many programs are capable of reading and editing text files. Common text editors include Microsoft Notepad and WordPad, which are bundled with Windows, and Apple TextEdit, which is included with Mac OS X.

Unknown Files

If you come across an unknown file type, first look up the file extension on FileInfo.com. If the file does not have an extension or you are unable to locate the file type, you can attempt to open the file in a text editor. If the file opens and displays fully readable text, it is a text file, which you have successfully opened.

If the file opens and displays mostly garbled text, it is a binary file. While the file is not mean to be opened in a text editor, there may be some clues within the text that reveal information about the file type, like in the PNG example above. This may help you determine what program you need to open the file correctly. Finally, if the file will not open in a text editor, it is a binary file that can only be opened by the appropriate program.



In C++, you open a file, you must first obtain a stream. There are the following three types of streams:
  • input
  • output
  • input/output
Create an Input Stream
To create an input stream, you must declare the stream to be of class ifstream. Here is the syntax:

ifstream fin;
Create an Output Stream
To create an output stream, you must declare it as class ofstream. Here is an example:
ofstream fout;
Create both Input/Output Streams
Streams that will be performing both input and output operations must be declared as class fstream. Here is an example:
fstream fio;
Opening a File in C++
Once a stream has been created, next step is to associate a file with it. And thereafter the file is available (opened) for processing.
Opening of files can be achieved in the following two ways :
  1. Using the constructor function of the stream class.
  2. Using the function open().
The first method is preferred when a single file is used with a stream. However, for managing multiple files with the same stream, the second method is preferred. Let's discuss each of these methods one by one.
Opening File Using Constructors
We know that a constructor of class initializes an object of its class when it (the object) is being created. Same way, the constructors of stream classes (ifstream, ofstream, or fstream) are used to initialize file stream objects with the filenames passed to them. This is carried out as explained here:
To open a file named myfile as an input file (i.e., data will be need from it and no other operation like writing or modifying would take place on the file), we shall create a file stream object of input type i.e., ifstream type. Here is an example:
ifstream fin("myfile", ios::in) ;
Now to read from this file, this stream object will be used using the getfrom operator (">>"). Here is an example:
ifstream fin("myfile", ios::in) ;


The above given statement creates an object, fin, of input file stream. The object name is a user-defined name (i.e., any valid identifier name can be given). After creating the ifstream object fin, the file myfile is opened and attached to the input stream, fin. Now, both the data being read from myfile has been channelised through the input stream object.
Now to read from this file, this stream object will be used using the getfrom operator (">>"). Here is an example:

char ch;
fin >> ch ;       // read a character from the file
float amt ;
fin >> amt ;       // read a floating-point number form the file

Similarly, when you want a program to write a file i.e., to open an output file (on which no operation can take place except writing only). This will be accomplish by
  1. creating ofstream object to manage the output stream
  2. associating that object with a particular file
Here is an example,
ofstream fout("secret" ios::out) ;// create ofstream object named as fout
This would create an output stream, object named as fout and attach the file secret with it.
Now, to write something to it, you can use << (put to operator) in familiar way. Here is an example,

int code = 2193 ;
fout << code << "xyz" ;    /* will write value of code
                        and "xyz" to fout's associated
                        file namely "secret" here. */
The connections with a file are closed automatically when the input and the output stream objects expires i.e., when they go out of scope. (For example, a global object expires when the program terminates). Also, you can close a connection with a file explicitly by using the close() method :
fin.close() ;     // close input connection to file
fout.close() ;     // close output connection to file
Closing such a connection does not eliminate the stream; it just disconnects it from the file. The stream still remains there. For example, after the above statements, the streams fin and fout still exist along with the buffers they manage. You can reconnect the stream to the same file or to another file, if required. Closing a file flushes the buffer which means the data remaining in the buffer (input or output stream) is moved out of it in the direction it is ought to be. For example, when an input file's connection is closed, the data is moved from the input buffer to the program and when an output file's connection is closed, the data is moved from the output buffer to the disk file.

Opening Files Using Open() Function

There may be situations requiring a program to open more than one file. The strategy for opening multiple files depends upon how they will be used. If the situation requires simultaneous processing of two files, then you need to create a separate stream for each file. However, if the situation demands sequential processing of files (i.e., processing them one by one), then you can open a single stream and associate it with each file in turn. To use this approach, declare a stream object without initializing it, then use a second statement to associate the stream with a file. For example,
ifstream fin;                        // create an input stream
fin.open("Master.dat", ios::in);     // associate fin stream with file Master.dat
:                                    // process Master.dat                       
fin.close();                         // terminate association with Master.dat
 
fin.open("Tran.dat", ios::in);       // associate fin stream with file Tran.dat
:                                    // process Tran.dat
fin.close();                         // terminate association
The above code lets you handle reading two files in succession. Note that the first file is closed before opening the second one. This is necessary because a stream can be connected to only one file at a time.

The Concept of File Modes

The filemode describes how a file is to be used : to read from it, to write to it, to append it, and so on.
When you associate a stream with a file, either by initializing a file stream object with a file name or by using the open() method, you can provide a second argument specifying the file mode, as mentioned below :
stream_object.open("filename", (filemode) ) ;
The second method argument of open(), the filemode, is of type int, and you can choose one from several constants defined in the ios class.
List of File Modes in C++
Following table lists the filemodes available in C++ with their meaning :
Constant
Meaning
Stream Type
ios :: in
It opens file for reading, i.e., in input mode.
Ifstream
ios :: out
It opens file for writing, i.e., in output mode.
This also opens the file in ios :: trunc mode, by default.
This means an existing file is truncated when opened,
i.e., its previous contents are discarded.
Ofstream
ios :: ate
This seeks to end-of-file upon opening of the file.
I/O operations can still occur anywhere within the file.
ofstream
ifstream
ios :: app
This causes all output to that file to be appended to the end.
This value can be used only with files capable of output.
Ofstream
ios :: trunc
This value causes the contents of a pre-existing file by the same name
to be destroyed and truncates the file to zero length.
Ofstream
ios :: nocreate
This cause the open() function to fail if the file does not already exist.
It will not create a new file with that name.
Ofstream
ios :: noreplace
This causes the open() function to fail if the file already exists.
This is used when you want to create a new file and at the same time.
Ofstream
ios :: binary
This causes a file to be opened in binary mode.
By default, files are opened in text mode.
When a file is opened in text mode,
various character translations may take place,
such as the conversion of carriage-return into newlines.
However, no such character translations occur in file opened in binary mode.
ofstream
ifstream
If the ifstream and ofstream constructors and the open() methods take two arguments each, how have we got by using just one in the previous examples ? As you probably have guessed, the prototypes for these class member functions provide default values for the second argument (the filemode argument). For example, the ifstream open() method and constructor use ios :: in (open for reading) as the default value for the mode argument, while the ofstream open() method and constructor use ios :: out (open for writing) as the default.
The fstream class does not provide a mode by default and, therefore, one must specify the mode explicitly when using an object of fstream class.

C++ Opening and Closing a File Example
Here is an example given, for the complete understanding on:
  • how to open a file in C++ ?
  • how to close a file in C++ ?
Let's look at this program.
/* C++ Opening and Closing a File
 * This program demonstrates, how
 * to open a file to store or retrieve
 * information to/from it. And then how
 * to close that file after storing
 * or retrieving the information to/from it. */
 
 
#include<conio.h>
#include<string.h>
#include<stdio.h>
#include<fstream.h>
#include<stdlib.h>
void main()
{
        ofstream fout;
        ifstream fin;
        char fname[20];
        char rec[80], ch;
        clrscr();
 
        cout<<"Enter file name: ";
        cin.get(fname, 20);
 
        fout.open(fname, ios::out);
 
        if(!fout)
        {
               cout<<"Error in opening the file "<<fname;
               getch();
               exit(1);
        }
        cin.get(ch);
 
        cout<<"\nEnter a line to store in the file:\n";
        cin.get(rec, 80);
        fout<<rec<<"\n";
        cout<<"\nThe entered line stored in the file successfully..!!";
        cout<<"\nPress any key to see...\n";
        getch();
        fout.close();
 
        fin.open(fname, ios::in);
        if(!fin)
        {
               cout<<"Error in opening the file "<<fname;
               cout<<"\nPress any key to exit...";
               getch();
               exit(2);
        }
 
        cin.get(ch);
        fin.get(rec, 80);
        cout<<"\nThe file contains:\n";
        cout<<rec;
        cout<<"\n\nPress any key to exit...\n";
        fin.close();
 
        getch();
}






#include <iostream> 
#include <conio.h>
  
#include <fstream> 

using namespace std; 

int main() 



    ofstream fout; 

    string line; 

    fout.open("sample.txt"); 

    fout << line << endl; 

    fout.close(); 

    return 0; 












File Handling through C++ Classes


In C++, files are mainly dealt by using three classes fstream, ifstream, ofstream available in fstream headerfile.
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.
Now the first step to open the particular file for read or write operation. We can open file by
1. passing file name in constructor at the time of object creation
2. using the open method
For e.g.
Open File by using constructor
ifstream (const char* filename, ios_base::openmode mode = ios_base::in);
ifstream fin(filename, openmode) by default openmode = ios::in
ifstream fin(“filename”);
Open File by using open method
Calling of default constructor
ifstream fin;
fin.open(filename, openmode)
fin.open(“filename”);

Mode

MEMBER  CONSTANT
STANDS FOR
ACCESS
in *
   input
File open for reading: the internal stream buffer supports input operations.
Out
output
File open for writing: the internal stream buffer supports output operations.
Binary
binary
Operations are performed in binary mode rather than text.
Ate
at end
The output position starts at the end of the file.
App
append
All output operations happen at the end of the file, appending to its existing contents.
Trunk
truncate
Any contents that existed in the file before it is open are discarded.





Default Open Modes :
ifstreamios::in
ofstreamios::out
fstreamios::in | ios::out
Problem Statement : To read and write a File in C++.
Examples:


Below is the implementation by using ifsream & ofstream classes.

/* File Handling with C++ using ifstream & ofstream class object*/
/* To write the Content in File*/
/* Then to read the content of file*/
#include <iostream>
  
/* fstream header file for ifstream, ofstream, 
  fstream classes */
#include <fstream>
  
using namespace std;
  
// Driver Code
int main()
{
    // Creation of ofstream class object
    ofstream fout;
  
    string line;
  
    // by default ios::out mode, automatically deletes
    // the content of file. To append the content, open in ios:app
    // fout.open("sample.txt", ios::app)
    fout.open("sample.txt");
  
    // Execute a loop If file successfully opened
    while (fout) {
  
        // Read a Line from standard input
        getline(cin, line);
  
        // Press -1 to exit
        if (line == "-1")
            break;
  
        // Write line in file
        fout << line << endl;
    }
  
    // Close the File
    fout.close();
  
    // Creation of ifstream class object to read the file
    ifstream fin;
  
    // by default open mode = ios::in mode
    fin.open("sample.txt");
  
    // Execute a loop until EOF (End of File)
    while (fin) {
  
        // Read a Line from File
        getline(fin, line);
  
        // Print line in Console
        cout << line << endl;
    }
  
    // Close the file
    fin.close();
  
    return 0;
}
Below is the implementation by using fstream class.
filt
/* File Handling with C++ using fstream class object */
/* To write the Content in File */
/* Then to read the content of file*/
#include <iostream>
  
/* fstream header file for ifstream, ofstream, 
   fstream classes */
#include <fstream>
  
using namespace std;
  
// Driver Code
int main()
{
    // Creation of fstream class object
    fstream fio;
  
    string line;
  
    // by default openmode = ios::in|ios::out mode
    // Automatically overwrites the content of file, To append
    // the content, open in ios:app
    // fio.open("sample.txt", ios::in|ios::out|ios::app)
    // ios::trunc mode delete all conetent before open
    fio.open("sample.txt", ios::trunc | ios::out | ios::in);
  
    // Execute a loop If file successfully Opened
    while (fio) {
  
        // Read a Line from standard input
        getline(cin, line);
  
        // Press -1 to exit
        if (line == "-1")
            break;
  
        // Write line in file
        fio << line << endl;
    }
  
    // Execute a loop untill EOF (End of File)
    // point read pointer at beginning of file
    fio.seekg(0, ios::beg);
  
    while (fio) {
  
        // Read a Line from File
        getline(fio, line);
  
        // Print line in Console
        cout << line << endl;
    }
  
    // Close the file
    fio.close();
  
    return 0;
}


No comments:

Post a Comment

Directory implementation

The selection of directory-allocation and directory-management algorithms significantly affects the efficiency, performance, and reliabil...