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

V-Unit V-Unit

The document covers file handling in C++ including file stream classes such as ifstream, ofstream, and fstream, detailing their functions for reading and writing data. It explains the differences between binary and ASCII files, as well as sequential and random access operations. Additionally, it introduces templates for generic programming, allowing the creation of functions and classes independent of data types.

Uploaded by

nallamaniartsbca
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views13 pages

V-Unit V-Unit

The document covers file handling in C++ including file stream classes such as ifstream, ofstream, and fstream, detailing their functions for reading and writing data. It explains the differences between binary and ASCII files, as well as sequential and random access operations. Additionally, it introduces templates for generic programming, allowing the creation of functions and classes independent of data types.

Uploaded by

nallamaniartsbca
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

lOMoARcPSD|45075901

V-UNIT

computer science & engg (Government Engineering College, Bhavnagar)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by bca nallamani (nallamaniartsbca@gmail.com)
lOMoARcPSD|45075901

UNIT - V
Files – File stream classes – file modes – Sequential Read / Write operations – Binary
and ASCII Files – Random Access Operation – Templates – Exception Handling - String
– Declaring and Initializing string objects – String Attributes – Miscellaneous
functions.

Files

A file is a collection of related data stored in a particular area on the disk.


Programs are employed in data transfer among file, console unit and the
program itself. For file manipulations, C++ uses file streams as an interface
between the programs and the files.
The stream that supplies data to the program is called as Input stream and
the stream that receives data from the program is called as Output stream. The
input operation uses the input stream to link between program and the input file.
The output operation uses the output stream to link program and the output file.
Example
#include <iostream>
#include <fstream>
File stream classes

Downloaded by bca nallamani (nallamaniartsbca@gmail.com)


lOMoARcPSD|45075901

1. ifstream Class
This class supports input operations on the files. It inherits the functions get( ),
getline( ), read( ), seekg( ) and tellg( ) from istream class. When the file is opened in
default mode, it contains open( ) function.
The functions of ifstream class are discussed below,
(i) get()
This function is used to read a single character from the file. The get pointer specifies
the character which has to be read from the file. This function belongs to fstream
class.
(ii) getline()
This function reads a line of text which ends with a newline character. It cam be called
using cin object as follows,
cin.getline( line, size), Where line is a variable that reads a line of text.
Size is number of characters to be read getline() function reads the input until it
encounters ‘\n’ or size ⎼1 characters are read. When ‘\n’ is read. it is not saved
instead it is replaced by the null character.
(iii) read()
This function reads a block of data of length specified by an argument ‘n’. This
function reads data sequentially. So when the EOF is reached before the whole block
is read then the buffer will contain the elements read until EOF.
General syntax,
istream & read(char*str, size n);

(iv) seekg()
This function is used to shift the input pointer (i.e., get) to the given location. It
belongs to ifstream. It is a file manipulator.
(v) tellg()
This function is used to determine the current position of the input pointer. It,
belongs to ifstream class.
2. ofstream Class
This class supports output operations on the files. It inherits the functions put(),
seekp(), tellp() and write() from ostream class. When the file is opened in default
mode, it also contains the open() function.
The functions of ofstream class are discussed below,

Downloaded by bca nallamani (nallamaniartsbca@gmail.com)


lOMoARcPSD|45075901

(i) put();
This function is used to write a single character to the file. A stream object specifies to
which file the character should be written. The character will be located at the
position specified by the put pointer. This function belongs to fstream class.

(ii) . seekp()
This function is used to shift the output pointer (i.e., put) to the given location. It
belongs to ofstream class. It is also a file manipulator.
(iii) tellp()
This function is used to determine the current position of the output pointer. It
belongs to ofstream class.

(iv) write()
This function displays a line on the screen. It is called using cout object as follows,
cout.write(line, size)
Where line is the string to be displayed.
Size is the number of characters to be displayed.
If the size of string is greater than the line (i.e., text to be displayed) then write()
function stop displaying on encountering null character but displays beyond the
bounds of line.

(3) fstream Class


This class provides support for both input and output operations on the files at the
same time. It inherits all the member functions of the istream and ostream classes
through iostream class. when a file is opened in default mode, it also contains open()
function.

(4) fstream Baseclass


This is the base class for ifstream, ofstream and fstream classes. It provides the
operations that are common to the file streams. It contains open( ) and class( )
functions.

(5) filebuf Class


This class is used to set the file buffers to read and write operations. it contains the
functions open() and close(). It also contains a constant named Openport which is
used
in opening of file stream classes using open() function.
(i) open()
This function is used to create new files as well as open existing files.

fstream myFile;

myFile.open(" filename.txt", ios::openMode);

General Form
Stream-object open (“file name”, mode);
Where, ‘mode’ specifies the purpose of opening a file. This ‘mode’ argument is
optional, if it is not given, then the prototype of member functions of the classes
ifstream and ostream uses the default, values for this argument. The default value are,
ios ∷ in for ifstream functions i.e., open in read only mode

Downloaded by bca nallamani (nallamaniartsbca@gmail.com)


lOMoARcPSD|45075901

and ios ∷ out for ofstream functions i.e., open.in write only mode.

(ii) close()
A file can be closed using member function close(). This function neither takes any
parameter nor returns any value.

file_object.close();

Opening a File
Before performing any operation on a file, you must first open it. If you need to write
to the file, open it using fstream or ofstream objects. If you only need to read from the
file, open it using the ifstream object.

The three objects, that is, fstream, ofstream, and ifstream, have the open() function
defined in them. The function takes this syntax:

open (file_name, mode);

 The file_name parameter denotes the name of the file to open.


 The mode parameter is optional. It can take any of the following values:

#include <iostream>

#include <fstream>
using namespace std;

int main() {

Downloaded by bca nallamani (nallamaniartsbca@gmail.com)


lOMoARcPSD|45075901

fstream my_file;

my_file.open("my_file", ios::out);

if (!my_file) {

cout << "File not created!";

else {

cout << "File created successfully!";

my_file.close();

return 0;

Output
File created successfully!
Code Explanation:

1. Include the iostream header file in the program to use its functions.
2. Include the fstream header file in the program to use its classes.
3. Include the std namespace in our code to use its classes without calling it.
4. Call the main() function. The program logic should go within its body.
5. Create an object of the fstream class and give it the name my_file.
6. Apply the open() function on the above object to create a new file. The out
mode allows us to write into the file.
7. Use if statement to check whether file creation failed.
8. Message to print on the console if the file was not created.
9. End of the body of if statement.
10. Use an else statement to state what to do if the file was created.
11. Message to print on the console if the file was created.
12. Apply the close() function on the object to close the file.
13. End of the body of the else statement.
14. The program must return value if it completes successfully.
15. End of the main() function body.

The read() and write() functions

Utilizing the read() and write() functions provided by C++ is an additional method for
reading and writing blocks of binary data. Their models are as follows:

istream &read((char *) &buf, int sizeof(buf));


ostream &write((char *) &buf, int sizeof(buf));

Downloaded by bca nallamani (nallamaniartsbca@gmail.com)


lOMoARcPSD|45075901

The read() function reads bytes from the associated stream of sizeof(buf) (or any
other integer value) and places them in the buffer pointed to by buf. The write()
function writes sizeof(buf) (or any other integer value) bytes from the buffer pointed
to by buf to the associated stream.

#include<iostream>
#include<fstream>
using namespace std;
main()
{
int rno,fee;
char name[50];
cout<<"Enter the Roll Number:";
cin>>rno;
cout<<"\nEnter the Name:";
cin>>name;
cout<<"\nEnter the Fee:";
cin>>fee;
ofstream fout("d:/student.doc");
fout<<rno<<"\t"<<name<<"\t"<<fee; //write data to the file student
fout.close();

ifstream fin("d:/student.doc");
fin>>rno>>name>>fee; //read data from the file student
fin.close();
cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;
return 0;
}
Sequential Read And Write
 C++ allows file manipulations command to accessed a file sequentially or
randomally. The data of sequential files must be access one characters at a time.
 To access thus specified by all the previous characters are read and ignored.
 There are member of function to perform read and write operations.
 The put() and get() functions are used to read or write a single character. The
read() and write() block of binary data.
The Put() And Get() Functions:
 The functions get() reads a single characters from the file.
 Pointered by the get() pointer.
 The put() function writes a character to the specified file. Example: #include
#include

Downloaded by bca nallamani (nallamaniartsbca@gmail.com)


lOMoARcPSD|45075901

The Read() And Write() Functions:


 The read() and write() function is used binary format of dat during operation.
 In binary format the data representation is same in the file and the system.
 The binary form follows quicks read and write because know conversion is
needed during the operations.
 The format a read() and write() function is follows:

Syntax:
In.read((char *)&p,size of(p));
Out.write((char *)&p,size of (p));

Binary And Ascii Files:


1. Text file (ASCII 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. Text file is human readable because everything
is stored in terms of text. It includes letters, numbers and other characters. In
text file, a special character, whose ASCII value is 26, is inserted after the last
character in the file to mark the end of file. In text file, the text and characters
are stored one character per byte.
Example: The integer value 12345 will occupy 4 bytes in memory but it will
occupy 6 bytes in text file including an EOF character.
2. 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. In
binary file everything is written in terms of 0 and 1, therefore binary file is not
human readable only computers can interpret. There is no special character
present in the binary mode files to mark the end of file. In binary file, the integer
value 1245 will occupy 2 bytes in memory as well as in file.
If ios::binary flag is specified during opening of a file, then the file is
considered to store a raw (binary) data. Otherwise the file is considered to be a
text file, also known as ascii file on operating systems using ASCII encoding for
characters. In ASCII file, a newline(n) character is converted into the carriage
return-linefeed combination before being written to the disk. In binary file, these
conversions will not take place. This type of processing is called text
autoformatting.
Example:
Program to write and read one integer and float value using text and binary
formats.
#include <iostream>
#include <fstream>
using namespace std;
int main()
int var1 = 12345;
float var2=6789.123;
//ASCII/text file processing
//write int and float value in to the file intfloat.txt
cout<<"ASCII file processing"<<endl;
of stream out;

Downloaded by bca nallamani (nallamaniartsbca@gmail.com)


lOMoARcPSD|45075901

out.open("textintfloat.txt", ios::out);
out<<varl<<<" "<<var2<<endl;
out.close();
int var3;
float var4;
// Read the data from the same file and print in console
ifstream in;
in.open("textintfloat.txt", ios::in);
in>>var3>>var4;
in.close();
cout<<"int value=”<<var3<<"; float value = "<<var4<<endl;
//if we open the textintfloat.txt file using any text editor we can see the same
values
//Binary file processing
cout<<"Binary file processing"<<endl;
downstream outbin;
outbin.open("binintfloat.bin", ios::out ios::binary);
outbin . write ( ( char * ) & varl , sizeof ( varl ) ) ;
outbin . write ( ( char * ) & var2 , sizeof ( var2 ) ) ;
outbin . close ( ) ;
var3 = 0;
var4 =0.;
// Read the data from file and print
ifstream inbin;
inbin.open("binintfloat.bin", ios::inlios::binary);
inbin.read((char *) &var3, sizeof (var3));
inbin.read((char *) &var4, sizeof (var4));
cout<<"int value = " <<var3<<"; float value = " <<var4<<endl;
inbin.close();
return 0;
Output:
ASCII file processing
int value = 12345; float value = 6789.12
Binary file processing
int value = 12345; float value = 6789.12

Random Access Operation


Unlike sequential access files, we can access random access files in any order.
For example we can play any mp3 songs recorded in the compact disk. The order of
recording has no way related with the order of playing the songs.
Random file access enables us to read or write any data in out disk file without
having to read or write each and every piece of records before it. It is possible to
quickly locate, modify, add and delete records easily in random access files. We can
use the same open and close functions to open and close random access files...

Downloaded by bca nallamani (nallamaniartsbca@gmail.com)


lOMoARcPSD|45075901

Template:
Templates are the foundation of generic programming, which involves writing
code in a way that is independent of any particular data type.
A template is a blueprint or formula for creating a generic class or a function.
The library containers like iterators and algorithms are examples of generic
programming and have been developed using template concept.
There is a single definition of each container, such as vector, but it is possible to
define many different kinds of vectors for example, vector<int> or vector <float>.
Templates are expanded at compiler time. This is like macros. The difference is,
compiler does type checking before template expansion. The source code contains
only function/class, but compiled code may contain multiple copies of same
function/class.
We can use templates to define functions as well as classes.
Definition Of Class Templates:
 The class templates can be defined as follows:
Syntax:
• Template class
• class classname
•{
• ….
•}
 Template class specifies the compiler the following class declaration use the
template data type.
 T is a variable of template type that can be used in the class to define
variable of template type.
 One or more variables can be declared by unseparated by comma.
 Templates can not be declared inside classes are functions. They must be
global.

Function Template
Function templates are special functions that can operate with generic types.
This allows us to create a function template whose functionality can be adapted to
more than one type or class without repeating the entire code for each type. The
idea is to pass data type as a parameter so that one don't need to write the same
code for different data types
This can be achieved using template parameters. A template parameter is a
special kind of parameter that can be used to pass a type as argument: just like
regular function parameters can be used to pass values to a function, template
parameters allow to pass also types to a function. These function templates can use
these parameters as if they were any other regular type.
Syntax to define template:
template <class identifier>
ret-type func-name (parameter list)
{
// body of the function
}
(or)

Downloaded by bca nallamani (nallamaniartsbca@gmail.com)


lOMoARcPSD|45075901

template <typename identifier>


ret-type func-name(parameter list)
{
// body of the function
}
Here, type is a placeholder name for a data type used by the function. This name can
be used within the function definition.
Program using function template that returns the maximum of two values:
#include <iostream>
#include <string>
using namespace std;
template <typename T>
T MaxofTwo (T a, T b)
{
if (a > b)
return a;
else
return b;
}
int main ()
{
int x = 10;
int y = 20;
cout << "MaxofTwo (x, y): "<<MaxofTwo (x, y) <<endl;
double dl =40.5;
double d2 =30.6;
cout << "MaxofTwo (d1, d2): "<<MaxofTwo (d1, d2) <<endl;
string strl "abc";
string str2 = "xyz";
cout << "MaxofTwo (strl, str2): "<<MaxofTwo (strl, str2);
return 0;
Output:
MaxofTwo(x, y): 20
MaxofTwo(d1, d2): 40.5
MaxofTwo(str1, str2): xyz
Overloading a Function Template
It is possible to overload the generic function means that the overloaded template
functions can differ in the parameter list.
#include <iostream>
using namespace std;
template<class A> void myprint (A x)
cout<<"Function with one parameter: x = : " <<x<<endl;
template<class A, class B> void myprint (A x,B y)
cout<<"Function with two parameters: x =" <<X << " y = "<<y<<endl;
int main()
{
myprint (30.23);
myprint('a',30.23);
return 0;

Downloaded by bca nallamani (nallamaniartsbca@gmail.com)


lOMoARcPSD|45075901

}
Output:
Function with one parameter: x = : 30.23
Function with two parameters: x = ay = 30.23
Class Template
Just like as function templates, it is possible to define class templates, which
are classes that can have members of the generic type, i..., members that use
template parameters as types. The template class serves to store elements of any
valid type.
The general form of a generic class declaration is shown here-
template <class type> class class-name
{
--
--
}
Here, type is the placeholder type name, which will be specified when a class is
instantiated. We can define more than one generic data type by using a comma-
separated list. We can create instance of the class by:
class_name<type>instance;
Program 1: Class template with one type:
#include <iostream>
using namespace std;
template<class X>
class Myclass
{
private:
X member1;
X member2;
public:
void add_values()
{
cout<<"Addition of memberl and member2 : “<< member1+member2<<endl;
}
Myclass (X a, X b).
{
member1 = a;
member2 = b;
}
};
int main()
{
Myclass <int> object1 (10,20);
object1.add_values();
Myclass <float> object2 (10.12,20.34);
object2.add_values();
return 0;
}

Downloaded by bca nallamani (nallamaniartsbca@gmail.com)


lOMoARcPSD|45075901

Output:
Addition of member1 and member2:30
Addition of member1 and member2: 30.46
Program 2: Class template with multiple types:
#include <iostream>
using namespace std;
template<class X, class Y>
class Myclass
{
private:
X member1;
Y member2;
public:
void display_values ()
{
cout<<"Value of memberl = :"<<member1<<<", member2 = :"<<member2<<<endl;
Myclass (X a, Y b)
{
Member1 = a;
member2 = b;
}
};
int main()
{
Myclass <int, float> object1 (10,20.12);
objectl.display_values();
return 0;
Output:
Value of member1 =: 10, member2 = : 20.12

Downloaded by bca nallamani (nallamaniartsbca@gmail.com)

You might also like