File Handling in C++

 Streams:

C/C++ IO are founded on streams, which are order of bytes rolling in and out of the programs. In input operations, data bytes flow from an input source  into the program. In output procedures, data bytes flow from the program to an output sink . Streams performances as an mediators between the programs and the real IO devices, in such the way that releases the programmers from management the actual devices, so as to record device independent IO operations.

C++ offers both the formatted and unformatted IO functions. In formatted or else high-level IO, bytes are grouped and transformed to types such as int, double, string or user-defined types. In unformatted or low-level IO, bytes are preserved as raw bytes and unconverted. Arranged IO operations are supported via overloading the stream insertion (<<) and stream extraction (>>) operators, which dowries a constant public IO interface.

  ofstream

The ofstream is a file stream class. It is used for control files. The ofstream is used to inscribe data to unlike files at different times.

  • To use ofstream header file fstream is built-in.  The insertion operator cast-off to write data to a file. to write to a file an object of type ofstream is formed. The general form  is,

ifstream object_name(“filename”);

  • The object_name is the name of the object formed. The filename is the tag of file to which data is to be written. The filename can hold the path where the file is kept.
  • If no path is specified then current directory is considered. If the file does not exist then new file is created when object is created. The contents of the current file are thrown away when object is formed. The file can be locked using close()

Example:

Output:

The statement

#include<fstream>

Contains a header file fstream in the program. The statement

ofstream outfile(“D:\\outfile1.txt”);

Makes an object outfile of type ofstream. The name of the file is outfile1.txt and its location is in D directory. The user go in his name and age. The statement

outfile << name << endl;

writes the name of the user to the file. The statement

outfile << age << endl;

writes the age of the user to the current file.

  ifstream

  • The ifstream is a file stream class used for file handling. To use ifstream header file fstream is normallyused. It is particularlyused for reading input from the file. to read from a file an object of type ifstream is made.

Syntax:

ifstream object_name(“filename”);

  • The object_name is the name of the object formed. The filename is the name of the file. E.g.,

ifstream  userstream(“file1.txt”);

here,The userstream is the name of the object plus file1.txt is the name of the file.

  • if the object is made file is repeatedly open. The grade of the file can be verified using ‘!’ operator along with ifstream object or else using is_open() which returns true if file is open.
  • The data can be read from the file by means of the insertion operator ‘>>’.
  • The end of file can be crisscrossed using function. It returns true when end of file is met.

Example:

Output:

The statement

#include<fstream>

Contains a header file fstream in the program. The statement

ofstream outfile(“D:\\outfile1.txt”);

Makes an object outfile of type ofstream. The name of the file is outfile1.txt and its location is in D directory. The user go in his name and age. The statement

outfile << name << endl;

writes the name of the user to the file. The statement

outfile << age << endl;

writes the age of the user to the current file.

  ifstream

  • The ifstream is a file stream class used for file handling. To use ifstream header file fstream is normallyused. It is particularlyused for reading input from the file. to read from a file an object of type ifstream is made.

Syntax:

ifstream object_name(“filename”);

  • The object_name is the name of the object formed. The filename is the name of the file. E.g.,

ifstream  userstream(“file1.txt”);

here,The userstream is the name of the object plus file1.txt is the name of the file.

  • if the object is made file is repeatedly open. The grade of the file can be verified using ‘!’ operator along with ifstream object or else using is_open() which returns true if file is open.
  • The data can be read from the file by means of the insertion operator ‘>>’.
  • The end of file can be crisscrossed using function. It returns true when end of file is met.

Example:

Output:

The declaration

#include<fstream>

Includes a header file fstream for using ifstream class. The statement

ifstream stream1(“D:\\file1.txt”);

Produces an object stream1 of type ifstream. The file is file1.txt which is situated in D directory. In the course of the creating of this object file is open. The statement

if(!stream1)

Checks whether an error is come across while opening a file. If a file is fruitfully open then it returns true and prints the message “File is effectively opened”. The statement

while(!stream1.eof())

Checks the whether the end of file is run into. The while loop is ended when end of file comes. The statement

stream1 >> a;

Uses an insertion operator to read text from file stream. The string a will cover the text.

  fstream

  • <fstream>library delivers functions for files, and we should just add #include <fstream> directives at the start of our program.
  • To open a file, a filestream object should first be formed. This is either an ofstreamobject for writing, or else an ifstream object for reading.
  • The statement of a filesream object for writing output arises with the ofstream, then a name for that filestream object monitored by parentheses identifying the file to write to: ofstream object_name (“file_name”);


Output:

Edsger Dijkstra: Made advances in algorithms, the semaphore (programming).
Donald Knuth: Wrote The Art of Computer Programming and created TeX.
Leslie Lamport: Formulated algorithms in distributed systems (e.g. the bakery algorithm).
Stephen Cook: Formalized the notion of NP-completeness.
  1. Opening a file:

Once a stream has been formed, next step is to companion a file with it. And afterwards the file is accessible (opened) for handling.

Opening of files can be achieved in the following two ways :

Opening File Using Constructors

  • the constructors of stream classes i.e.ifstream, ofstream, or else fstream are used to make ready file stream objects with the filenames passed to them.
  • To open a file named myfile as an input file we shall produce a file stream object of input type i.e., ifstream type.

example:

ifstream fin(“myfile”, ios::in) ;

  • here,produces an object, fin, of input file stream. The object name is a user-defined name .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 channelized through the input stream object.
  • To read from this file, this stream object will be used using the get fromoperator (“>>”).

example:

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

  • Likewise, 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

example,

ofstream fout(“secret” ios::out) ;     // create ofstream object named as fout

2.associating that object with a particular file

example,

int code = 2193 ;fout << code << “xyz” ;    /* will write value of code                                                             and “xyz” to fout’s associated                                                             file namely “secret” here. */

  • you can close a connection with a file explicitly by using the close() method :

fin.close() ;     // close input connection to filefout.close() ;     // close output connection to file

Opening Files Using Open() Function

  • There may be circumstancesneeding a program to open more than one file.. If the situation have need ofcoinciding processing of two files, then you want to create a separate stream for each file.
  • Though, if the situation demands successive processing of files , then you can open a single stream and subordinate it with each file in turn.

For example,

ifstream fin;                        // create an input streamfin.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.datfin.close();                         // terminate association

here reading two files in series.  the first file is closed earlier opening the second one. This is essentialsince a stream can be connected to only one file at a time.

The Concept of File Modes

The filemode defines how a file is to be used : to read from it, to write to it, to append it, etc

When you subordinate a stream with a file, either by preparing a file stream object with a file name or else 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 current file is abbreviated when opened,
i.e., its previous contents are cast-off.
ofstream
ios :: ate This seeks to end-of-file upon opening of the file.
I/O operations can still happen 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 accomplished 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.
Though, no such character translations arise 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 perhaps have predicted, the prototypes for these class member functions offer 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 afford a mode by default and, therefore, one must agree the mode explicitly when using an object of fstream class.

Both ios::ate and ios::app place you at the end of the file just unlocked. The difference amongst the two is that the ios::app mode allows you to add data to the end of the file only, when the ios::ate mode lets you write data anywhere in the file, even over old data.

You can conglomerate two or else more filemode constants using the C++ bitwise OR operator (symbol |).example :

ofstream fout;fout.open(“Master”, ios :: app | ios :: nocreate);

will open a file in the append mode if the file exists and will abandon the file opening operation if the file does not exist.

To open a binary file, you need to specify ios :: binary along with the file mode, e.g.,

fout.open(“Master”, ios :: app | ios :: binary);

or,

fout.open(“Main”, ios :: out | ios :: nocreate | ios :: binary);

 Reading a file

Read File in C++

To read a file in C++ programming, you have to first open that file using the function open() and then start reading the file’s content as shown here in the following program.

C++ Programming Code to Read File

First make a textual file named “filename.txt” in your BIN (for TurboC++ user) folder present inside TurboC++directory, to open this file for reading.

Following C++ program opens a file named filename.txt to read the content present inside this file, if there is an error in opening a file then program puts a message on the screen for the error, and if the file will be read then it will display the file (content of the file) but this program limits to only one line of the file which is to be read. To know more, go to 2nd next program, which will clear your doubt, that program will read a file and display the contents of it. For now, go through the following program which will read a file and display its content on the screen:

 

Write To File in C++

To write some content in a file using C++ programming, you have to enter the file name with extension to open that file using the function open(), then after opening the desired file, again ask to the user to enter some content (some line of text) to store in the file. And at last, close the file after use using the function close() as shown in the following program.

C++ Programming Code to Write Content to File

Following C++ program ask to the user to enter file name to open (if file present inside the directory) or create (if file not present inside the directory), then ask to the user to enter some line of text to store these lines inside the files for further use :

Output:

After writing the above four line, you will press double ENTER key (line break), your all the four line will be written in the file named file.txt and output screen backed to the source code. Now go to the next program to know how to read this file and display its content on the screen.

 Closing a file

  • A file is closed by detaching it with the stream it is accompanying with. The close() function accomplishes this task and it takes the following general form :

stream_object.close();

if a file Master is linked with an ofstream object fout, its connections with the stream fout can be ended by the following statement :

fout.close() ;

Let’s look at this program.

Output:

 Append / Join to a file

  • To join two files in C++ programming, first open the two file and start copying the content of first file to the third file(objective file) after this start adding the content of second file to the third file (objective file).

Output:

 

Leave A Comment

Your email address will not be published. Required fields are marked *