Opening and Closing of Files in C++
File is a collection of data or a set of characters or may be a text or a program. Basically, there are two types of files in the C++: sequential files and random access files. The sequential files are very easy to create than random access files. In sequential files the data or text will be stored or read back sequentially. In random access fi les, data can be accessed and processed randomly.
The header file, <fstream> supports the highly sophisticated input/output stream processing techniques and to implement input/output for the advanced language features such as classes, derived classes, function overloading, virtual function and multiple inheritance.
- ifstream - to read a stream of object from a specified file
- ofstream - to write a stream of object on a specified file
- fstream - both to read and write a stream of objects on a specified file
The header fi le <fstream> is a new class which consists of basic fi le operation routines and functions. The fstream, ifstream and ofstream are called as derived class as these class objects are already defined in the basic input and output class namely <iostream>.
The following examples illustrate how files can be opened for reading and writing in C++. The member function open () is used to create a file pointer for opening a fi le in the disk.
(a) ifstream: The header file <ifstream> is a derived class from the base class of istream and is used to read a stream of objects from a file. The following program segment shows how a file is opened to read a class of stream objects from a specified file:
#include <fstream>
using namespace std;
int main()
{
ifstream in le;
in le.open(“data_ le”); // opening a le
-------
-------
return 0;
}
(b) ofstream: The header file <ofstream> is derived from the base class of ostream and is used to write a stream of objects in a fi le. The following program segment illustrates how a file is opened to write a class of stream objects on a specified file:
#include <fstream>
using namespace std;
int main()
{
ofstream in le;
in le.open(“data_ le”);
-------
-------
return 0;
}
(c) fstream: The header file <fstream> is a derived class from the base class of iostream and is used for both reading and writing a stream of objects on a file. The include <fstream> automatically includes the header file <iostream>. The following program segments shows how a file is opened for both reading and writing a class of stream objects from a specified file.
#include <fstream>
using namespace std;
int main()
{
fstream in le;
in le.open(“data_ le”, ios::in | ios::out);
-------
-------
return 0;
}
When a file is opened for both reading and writing, the I/O streams keep track of two fi le pointers — one for input operation and the other for output operation.
Name of the member function and Meaning
- ios:: in open a fi le for reading
- ios:: out open a fi le for writing
- ios:: app append at the end of a fi le
- ios:: ate seek to the end of a fi le upon opening instead of beginning
- ios:: trunc delete a fi le if it exists and recreate it
- ios:: nocreate open a fi le if a fi le does not exist
- ios:: replace open a fi le if a fi le does exist
- ios:: binary open a fi le for binary mode; default is text
(d)Closing a File
The member function close () is used to close a file which has been opened for file processing such as to read, to write and for both to read and write. The close () member function is called automatically by the destructor functions. However, one may call this member function to close the file explicitly. The close member function will not contain any arguments. The general syntax of the close () member function is:
#include <fstream>
using namespace std;
int main()
{
fstream in le;
in le.open(“data_ le”, ios::in | ios::out);
-------
-------
in le.close (); // calling to close the le
return 0;
}
STREAM STATE MEMBER FUNCTIONS
In C++, file stream classes inherit a stream state member from the ios class. The stream state member functions give the information status like end of file has been reached or file open failure and so on. Thefollowing stream state member functions are used for checking the open failure if any, when one attempts to open a file from the diskette.
(a) eof(): The eof() stream state member function is used to check whether a file pointer has reached the end of a file character or not. If it is successful, eof() member function returns a nonzero, otherwise returns 0. The general syntax of the eof() stream state member function is:
#include <fstream>
using namespace std;
int main()
{
ifstream in le;
in le.open(“text”);
while (!in le.eof()) {
-------
-------
}
return 0;
}
(b) fail(): The fail() stream state member function is used to check whether a file has been opened for input or output successfully, or any invalid operations are attempted or there is an unrecoverable error. If it fails, it returns a nonzero character. The general syntax of the fail () stream state member function is:
#include <fstream>
using namespace std;
int main()
{
ifstream in le;
in le.open(“text”);
while (!in le.fail()) {
cout << “ couldn’t open a le ” << endl;
continue;
-------
-------
}
return 0;
}
(c) bad(): The bad() stream state member function is used to check whether any invalid file operations has been attempted or there is an unrecoverable error. The bad() member function returns a nonzero if it is true; otherwise returns a zero. The general syntax of the bad() stream state member function is:
#include <fstream>
#include <cstdlib>
using namespace std;
int main()
{
ifstream in le;
in le.open(“text”);
if (in le.bad() ) {
cerr << “ open failure ” << endl;
exit(1);
}
-------
-------
}
(d) good(): The good() stream state member function is used to check whether the previous file operation has been successful or not. The good() returns a nonzero if all stream state bits are zero. The general syntax of the good() stream state member function is:
#include <fstream>
#include <cstdlib>
using namespace std;
int main()
{
ifstream in le;
in le.open(“text”);
if (in le.good()) {
-------
-------
}
}
READING/WRITING A CHARACTER FROM A FILE
(a) get(): The get() member function is used to read an alphanumeric character from a specified file. The general syntax of the get() function is:
#include <fstream>
using namespace std;
int main()
{
ifstream in le;
char ch;
in le.open (“text”);
-------
-------
while (( !in le.eof()) {
ch = in le.get()
-------
-------
} // end of while loop
}
(b) put(): The put() member function is used to write a character to a specified file or a specified output stream. The general syntax of the put() member function is:
#include <fstream>
using namespace std;
int main()
{
ofstream out le;
char ch;
out le.open (“text”);
-------
-------
while (( !iout le.eof()) {
ch = out le.get()
cout.put(ch) // display a character onto a screen
-------
-------
}
}
Example 1.
A program to demonstrate the writing of a set of lines to a specified file, namely, “text.dat”.
//storing a text on a le
#include <fstream>
using namespace std;
int main()
{
ofstream out le;
out le.open(“text.dat”);
out le << “ this is a test \n”;
out le << “ program to store \n”;
out le << “ a set of lines onto a le \n”;
out le.close();
return 0;
}
The contents of the “text.dat” file
this is a test
program to store
a set of lines onto a le
Example 2.
A program to illustrate the writing of a set of lines to a user-defined file where name of the file is specified in the user-defined mode.
//storing a text on a speci ed le
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream out le;
char fname[10];
cout << “ enter a le name to be opened ?\n”;
cin >> fname;
out le.open(fname);
out le << “ this is a test \n”;
out le << “ program to store \n”;
out le << “ a set of lines onto a le \n”;
out le.close();
return 0;
}
Output of the above program
enter a le name to be opened
data
The contents of the le called “data”
this is a test
program to store
a set of lines onto a le
Example 3.
A program to read a set of lines from the keyboard and to store it on a specified file.
//reading a text and store it on a speci ed le
#include <iostream>
#include <fstream>
using namespace std;
const int MAX = 2000;
int main()
{
ofstream out le;
char fname[10],line[MAX];
cout << “ enter a le name to be opened ?\n”;
cin >> fname;
out le.open(fname);
cout << “ enter a set of lines and terminate with @\n”;
cin.get(line,MAX,’@’);
cout << “ given input \n”;
cout << line;
cout << “ storing onto a le ....\n”;
out le << line;
out le.close();
return 0;
}
Output of the above program
enter a le name to be opened?
data
enter a set of lines and terminate with @
this
is a
test program
by Ravich
@
given input
this
is a
test program
by Ravich
storing onto a le ....
Example 4.
A program to demonstrate how to read a text file and to display the contents on the screen.
// reading and displaying a text le
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstdlib>
using namespace std;
int main()
{
ifstream in le;
char fname1[10];
char ch;
cout << “ enter a le name ? \n”;
cin >> fname1;
in le.open(fname1);
if (in le.fail()) {
cerr << “ No such a le exists \n”;
exit(1);
}
while ( !in le.eof()) {
ch = (char)in le.get();
cout.put(ch);
}
in le.close();
return 0;
}
Example 5.
A program to copy the contents of a text file into another.
// le copy
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstdlib>
using namespace std;
int main()
{
ofstream out le;
ifstream in le;
char fname1[10],fname2[10];
char ch;
cout << “ enter a le name to be copied ? \n”;
cin >> fname1;
cout << “ new le name ? \n”;
cin >> fname2;
in le.open(fname1);
if (in le.fail()) {
cerr << “ No such a le exists \n”;
exit(1);
}
out le.open(fname2);
if (out le.fail()) {
cerr << “ unable to create a le \n”;
exit(1);
}
while ( !in le.eof()) {
ch = (char)in le.get();
out le.put(ch);
}
in le.close();
out le.close();
return 0;
}
Output of the above program
enter a le name to be copied?
data
new le name?
tempdata
Example 6.
A program to perform the deletion of white spaces such as horizontal tab, vertical tab, space, line feed, new line and carriage return, from a text file and to store the contents of the file without white spaces on another file.
// deleting white spaces from a text le
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstdlib>
using namespace std;
int main()
{
ofstream out le;
ifstream in le;
char fname1[10],fname2[10];
char ch;
cout << “ enter a le name to be copied ? \n”;
cin >> fname1;
cout << “ new le name ? \n”;
cin >> fname2;
in le.open(fname1);
if (in le.fail()) {
cerr << “ No such a le exists \n”;
exit(1);
}
out le.open(fname2);
if (out le.fail()) {
cerr << “ unable to create a le \n”;
exit(1);
}
while ( !in le.eof()) {
ch = (char)in le.get();
if (ch == ‘ ’ || ch == ‘\t’ || ch == ‘\n’)
;
else
out le.put(ch);
}
in le.close();
out le.close();
return 0;
}
Output of the above program
content of the input le
this is a
test program
by Sampath K Reddy
content of the output le
thisisatestprogrambySampathKReddy
Example 7.
A program to convert a lower case character to an upper case character of a text file.
// converting a lower case to upper case letters
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstdlib>
#include <cctype>
using namespace std;
int main()
{
ofstream out le;
ifstream in le;
char fname1[10],fname2[10];
char ch,uch;
cout << “ enter a le name to be copied ? \n”;
cin >> fname1;
cout << “ new le name ? \n”;
cin >> fname2;
in le.open(fname1);
if (in le.fail()) {
cerr << “ No such a le exists \n”;
exit(1);
}
out le.open(fname2);
if (out le.fail()) {
cerr << “ unable to create a le \n”;
exit(1);
}
while ( !in le.eof()) {
ch = (char)in le.get();
uch = toupper(ch);
out le.put(uch);
}
in le.close();
out le.close();
return 0;
}
Input file
this is a
test program
by Sampath K Reddy
Output file
THIS IS A
TEST PROGRAM
BY SAMPATH K REDDY

0 comments
Post a Comment