0% found this document useful (0 votes)
21 views14 pages

C++ Unit V

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 14

I YEAR – II SEMESTER

COURSE CODE: 7BCE2C1

CORE COURSE-III–OBJECT ORIENTED PROGRAMMING WITH C++

Unit V
Classes of file stream operations – Opening and Closing files – Detecting end of file
– More about open() function – File modes, File pointers and their manipulation – Sequential
input and output operations – Command-line arguments- Templates: class templates and
function templates.

Classes of file stream operation:

we have been using the iostream standard library, which provides cin and cout methods for
reading from standard input and writing to standard output respectively.

Sr.No Data Type & Description

1 Ofstream
This data type represents the output file stream and is used to create files and to write
information to files.

2 Ifstream
This data type represents the input file stream and is used to read information from files.

3 Fstream
This data type represents the file stream generally, and has the capabilities of both
ofstream and ifstream which means it can create files, write information to files, and read
information from files.

To perform file processing in C++, header files <iostream> and <fstream> must be included
in your C++ source file.

Opening a File
A file must be opened before you can read from it or write to it.
Either ofstream or fstream object may be used to open a file for writing. And ifstream
object is used to open a file for reading purpose only.

M.Karthika M.Sc.,M.phil
Vidhyaa Giri College of Arts and Science,Puduvayal Page 1
Following is the standard syntax for open() function, which is a member of fstream,
ifstream, and ofstream objects.
void open(const char *filename, ios::openmode mode);
Here, the first argument specifies the name and location of the file to be opened and the
second argument of the open() member function defines the mode in which the file should
be opened.

Sr.No Mode Flag & Description

1 ios::app
Append mode. All output to that file to be appended to the end.

2 ios::ate
Open a file for output and move the read/write control to the end of the file.

3 ios::in
Open a file for reading.

4 ios::out
Open a file for writing.

5 ios::trunk
If the file already exists, its contents will be truncated before opening the file.

You can combine two or more of these values by ORing them together. For example if you
want to open a file in write mode and want to truncate it in case that already exists,
following will be the syntax −
ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc );
Similar way, you can open a file for reading and writing purpose as follows −
fstream afile;
afile.open("file.dat", ios::out | ios::in );

Closing a File
When a C++ program terminates it automatically flushes all the streams, release all the
allocated memory and close all the opened files. But it is always a good practice that a
programmer should close all the opened files before program termination.

M.Karthika M.Sc.,M.phil
Vidhyaa Giri College of Arts and Science,Puduvayal Page 2
Following is the standard syntax for close() function, which is a member of fstream,
ifstream, and ofstream objects.
void close();

Writing to a File
While doing C++ programming, you write information to a file from your program using the
stream insertion operator (<<) just as you use that operator to output information to the
screen. The only difference is that you use an ofstream or fstream object instead of
the cout object.

Reading from a File


You read information from a file into your program using the stream extraction operator
(>>) just as you use that operator to input information from the keyboard. The only
difference is that you use an ifstream or fstream object instead of the cin object.

Read and Write Example


Following is the C++ program which opens a file in reading and writing mode. After writing
information entered by the user to a file named afile.dat, the program reads information from
the file and outputs it onto the screen −
Live Demo
#include <fstream>
#include <iostream>
using namespace std;

int main () {
char data[100];

// open a file in write mode.


ofstream outfile;
outfile.open("afile.dat");

cout << "Writing to the file" << endl;


cout << "Enter your name: ";
cin.getline(data, 100);

// write inputted data into the file.


outfile << data << endl;

cout << "Enter your age: ";


cin >> data;
cin.ignore();

// again write inputted data into the file.

M.Karthika M.Sc.,M.phil
Vidhyaa Giri College of Arts and Science,Puduvayal Page 3
outfile << data << endl;

// close the opened file.


outfile.close();

// open a file in read mode.


ifstream infile;
infile.open("afile.dat");

cout << "Reading from the file" << endl;


infile >> data;

// write the data at the screen.


cout << data << endl;

// again read the data from the file and display it.
infile >> data;
cout << data << endl;

// close the opened file.


infile.close();

return 0;
}
When the above code is compiled and executed, it produces the following sample input and
output −
$./a.out
Writing to the file
Enter your name: Zara
Enter your age: 9
Reading from the file
Zara
9
Above examples make use of additional functions from cin object, like getline() function to
read the line from outside and ignore() function to ignore the extra characters left by
previous read statement.

Deleting end of file:

C++ provides a special function, eof( ), that returns nonzero (meaning TRUE)
when there are no more data to be read from an input file stream, and zero
(meaning FALSE) otherwise.

Rules for using end-of-file (eof( )):

M.Karthika M.Sc.,M.phil
Vidhyaa Giri College of Arts and Science,Puduvayal Page 4
1. Always test for the end-of-file condition before processing data
read from an input file stream.
a. use a priming input statement before starting the loop
b. repeat the input statement at the bottom of the loop body
2. Use a while loop for getting data from an input file
stream. A for loop is desirable only when you know the exact
number of data items in the file, which we do not know.

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

int main(void)
{
int data; // file contains an undermined number of integer values
ifstream fin; // declare stream variable name

fin.open("myfile",ios::in); // open file


assert (!fin.fail( ));
fin >> data; // get first number from the file (priming the input
statement)
// You must attempt to read info prior to an eof( ) test.
while (!fin.eof( )) //if not at end of file, continue reading numbers
{
cout<<data<<endl; //print numbers to screen
fin >> data; //get next number from file
}
fin.close( ); //close file
assert(!fin.fail( ));
return 0;
}

File Modes:

In C++, for every file operation, exists a specific file mode. These file modes allow us
to create, read, write, append or modify a file. The file modes are defined in the class ios.
Let's see all these different modes in which we could open a file on disk.

File Modes Description

ios::in Searches for the file and opens it in the read mode only(if the file is
found).
ios::out
M.Karthika M.Sc.,M.phil
Vidhyaa Giri College of Arts and Science,Puduvayal Page 5
Searches for the file and opens it in the write mode. If the file is found,
its content is overwritten. If the file is not found, a new file is
created. Allows you to write to the file.

Searches for the file and opens it in the append mode i.e. this mode allows
ios::app
you to append new data to the end of a file. If the file is not found, a new
file is created.

"ios::binary" Searches for the file and opens the file(if the file is found) in a binary mode
to perform binary input/output file operations.

Searches for the file, opens it and positions the pointer at the end of the file.
ios::ate
This mode when used with ios::binary, ios::in and ios::out modes, allows
you to modify the content of a file.

"ios::trunc" Searches for the file and opens it to truncate or deletes all of its content(if
the file is found.

"ios::nocreate" Searches for the file and if the file is not found, a new file will not be
created.

File Pointer:

Every file maintains two pointers called get_pointer (in input mode file) and put_pointer (in
output mode file) which tells the current position in the file where reading or writing will
takes place. (A file pointer in this context is not like a C++ pointer but it works like a book-
mark in a book.). These pointers help attain random access in file. That means moving
directly to any location in the file instead of moving through it sequentially.

The seekg(), seekp(), tellg() and tellp() Functions

In C++, random access is achieved by manipulating seekg(), seekp(), tellg() and tellp()
functions. The seekg() and tellg() functions allow you to set and examine the get_pointer, and
the seekp() and tellp() functions perform these operations on the put_pointer.

The seekg() and tellg() functions are for input streams (ifstream) and seekp() and tellp()
functions are for output streams (ofstream). However, if you use them with an fstream object
then tellg() and tellp() return the same value. Also seekg() and seekp() work the same way in
an fstream object. The most common forms of these functions are :

istream & seekg(long); Form 1


seekg()
istream & seekg(long, seek_dir); Form 2

M.Karthika M.Sc.,M.phil
Vidhyaa Giri College of Arts and Science,Puduvayal Page 6
ofstream & seekp(long);
seekp()
ofstream & seekp(long, seek_dir);

The seekg() or seekp(), when used according to Form 1, then it moves the get_pointer or
put_pointer to an absolute position. Here is an example:

ifstream fin;
ofstream fout;
: // file opening routine
fin.seekg(30); // will move the get_pointer (in ifstream) to byte number 30 in the file
fout.seekp(30); // will move the put_pointer (in ofstream) to byte number 30 in the file

When seekg() or seekp() function is used according to Form 2, then it moves the get_pointer
or put_pointer to a position relative to the current position, following the definition of
seek_dir. Since, seek_dir is an enumeration defined in the header file iostream.h, that has the
following values:

Sequential Input / Output Operation:

The file stream classes support a number of member functions for performing the input and
output operations on files. The functions get() and put() are capable of handling a single
character at a time. The function getline() lets you handle multiple characters at a time.
Another pair of functions i.e., read() and write() are capable of reading and writing blocks of
binary data.

The get(), getline() and put() Functions

The functions get() and put() are byte-oriented. That is, get() will read a byte of data and put()
will write a byte of data. The get() has many forms, but the most commonly used version is
shown here, along with put() :

istream & get(char & ch) ;


ostream & put(char ch) ;

The get() function reads a single character from the associated stream and puts that value in
ch. It returns a reference to the stream. The put() writes the value of ch to the stream and
returns a reference to the stream.

The following program displays the contents of a file on the screen. It uses the get() function :

M.Karthika M.Sc.,M.phil
Vidhyaa Giri College of Arts and Science,Puduvayal Page 7
/* C++ Sequential Input/Output Operations on Files */

#include<iostream.h>
#include<stdlib.h>
#include<fstream.h>
#include<conio.h>
void main()
{
char fname[20], ch;
ifstream fin; // create an input stream
clrscr();

cout<<"Enter the name of the file: ";


cin.get(fname, 20);
cin.get(ch);

fin.open(fname, ios::in); // open file


if(!fin) // if fin stores zero i.e., false value
{
cout<<"Error occurred in opening the file..!!\n";
cout<<"Press any key to exit...\n";
getch();
exit(1);
}

while(fin) // fin will be 0 when eof is reached


{
fin.get(ch); // read a character
cout<<ch; // display the character
}

cout<<"\nPress any key to exit...\n";


fin.close();
getch();
}

Here is the sample output of the above C++ program. Let's suppose that the file contain the
following information:

Command Line Arguments:


M.Karthika M.Sc.,M.phil
Vidhyaa Giri College of Arts and Science,Puduvayal Page 8
The most important function of C/C++ is main() function. It is mostly defined with a
return type of int and without parameters :
int main() { /* ... */ }
We can also give command-line arguments in C and C++. Command-line arguments
are given after the name of the program in command-line shell of Operating
Systems.
To pass command line arguments, we typically define main() with two arguments :
first argument is the number of command line arguments and second is list of
command-line arguments.
int main(int argc, char *argv[]) { /* ... */ }
or
int main(int argc, char **argv) { /* ... */ }
• argc (ARGument Count) is int and stores number of command-line arguments
passed by the user including the name of the program. So if we pass a value to a
program, value of argc would be 2 (one for argument and one for program name)
• The value of argc should be non negative.
• argv(ARGument Vector) is array of character pointers listing all the arguments.
• If argc is greater than zero,the array elements from argv[0] to argv[argc-1] will
contain pointers to strings.
• Argv[0] is the name of the program , After that till argv[argc-1] every element is
command -line arguments.

For better understanding run this code on your linux machine.

// Name of program mainreturn.cpp

#include <iostream>

using namespace std;

int main(int argc, char** argv)

M.Karthika M.Sc.,M.phil
Vidhyaa Giri College of Arts and Science,Puduvayal Page 9
cout << "You have entered " << argc

<< " arguments:" << "\n";

for (int i = 0; i < argc; ++i)

cout << argv[i] << "\n";

return 0;

Input:
$ g++ mainreturn.cpp -o main
$ ./main geeks for geeks
Output:
You have entered 4 arguments:
./main
geeks
for
geeks

M.Karthika M.Sc.,M.phil
Vidhyaa Giri College of Arts and Science,Puduvayal Page 10
Templates:

A template is a simple and yet very powerful tool in C++. The simple idea is to pass
data type as a parameter so that we don’t need to write the same code for different
data types. For example, a software company may need sort() for different data
types. Rather than writing and maintaining the multiple codes, we can write one
sort() and pass data type as a parameter.
C++ adds two new keywords to support templates: ‘template’ and ‘typename’. The
second keyword can always be replaced by keyword ‘class’.
How templates work?
Templates are expanded at compiler time. This is like macros. The difference is,
compiler does type checking before template expansion. The idea is simple, source
code contains only function/class, but compiled code may contain multiple copies of
same function/class.

Function Templates We write a generic function that can be used for different data
types. Examples of function templates are sort(), max(), min(), printArray().
Know more on Generics in C++

#include <iostream>

using namespace std;

M.Karthika M.Sc.,M.phil
Vidhyaa Giri College of Arts and Science,Puduvayal Page 11
// One function works for all data types. This would work

// even for user defined types if operator '>' is overloaded

template <typename T>

T myMax(T x, T y)

return (x > y)? x: y;

int main()

cout << myMax<int>(3, 7) << endl; // Call myMax for int

cout << myMax<double>(3.0, 7.0) << endl; // call myMax for double

cout << myMax<char>('g', 'e') << endl; // call myMax for char

return 0;

Output:
7
7
G

Class Templates
M.Karthika M.Sc.,M.phil
Vidhyaa Giri College of Arts and Science,Puduvayal Page 12
Like function templates, class templates are useful when a class defines something that is
independent of the data type. Can be useful for classes like LinkedList, BinaryTree, Stack,
Queue, Array, etc.
Following is a simple example of template Array class.

#include <iostream>

using namespace std;

template <typename T>

class Array {

private:

T *ptr;

int size;

public:

Array(T arr[], int s);

void print();

};

template <typename T>

Array<T>::Array(T arr[], int s) {

ptr = new T[s];

size = s;

M.Karthika M.Sc.,M.phil
Vidhyaa Giri College of Arts and Science,Puduvayal Page 13
for(int i = 0; i < size; i++)

ptr[i] = arr[i];

template <typename T>

void Array<T>::print() {

for (int i = 0; i < size; i++)

cout<<" "<<*(ptr + i);

cout<<endl;

int main() {

int arr[5] = {1, 2, 3, 4, 5};

Array<int> a(arr, 5);

a.print();

return 0;

Output:
12345

M.Karthika M.Sc.,M.phil
Vidhyaa Giri College of Arts and Science,Puduvayal Page 14

You might also like