SlideShare a Scribd company logo
1 of 10
UNIT – V FILES
File Handling In C++
Files are used to store data in a storage device permanently. File handling
provides a mechanism to store the output of a program in a file and to perform
various operations on it.
A stream is an abstraction that represents a device on which operations of input
and output are performed. A stream can be represented as a source or
destination of characters of indefinite length depending on its usage.
In C++ we have a set of file handling methods. These include ifstream,
ofstream, and fstream.
These classes are derived from fstrembase and from the corresponding iostream
class. These classes, designed to manage the disk files, are declared in fstream
and therefore we must include fstream and therefore we must include this file in
any program that uses files.
In C++, files are mainly dealt by using three classes fstream, ifstream, ofstream.
ofstream: This Stream class signifies the output file stream and is applied to
create files for writing information to files
ifstream: This Stream class signifies the input file stream and is applied for
reading information from files
fstream: This Stream class can be used for both read and write from/to files.
C++ provides us with the following operations in File Handling: - MODES
Creating a file: open(), Reading data: read(), Writing new data: write(), Closing
a file: close()
Opening a File
Generally, the first operation performed on an object of one of these classes is to associate it to
a real file. This procedure is known to open a file.
We can open a file using any one of the following methods:
1. First is bypassing the file name in constructor at the time of object creation.
2. Second is using the open() function.
To open a file use
open() function
Syntax - void open(const char* file_name,ios::openmode mode);
Here, the first argument of the open function defines the name and format of the file with the
address of the file.
The second argument represents the mode in which the file has to be opened. The following
modes are used as per the requirements.
Modes Description
In - Opens the file to read(default for ifstream)
Out-Opens the file to write(default for ofstream)
Binary-Opens the file in binary mode
App-Opens the file and appends all the outputs at the end
Ate-Opens the file and moves the control to the end of the file
Trunc-Removes the data in the existing file
Nocreate-Opens the file only if it already exists
Noreplace-Opens the file only if it does not already exist
Example
fstream new_file;
new_file.open(“newfile.txt”, ios::out);
In the above example, new_file is an object of type fstream, as we know fstream is a class so we
need to create an object of this class to use its member functions. So we create new_file object
and call open() function. Here we use out mode that allows us to open the file to write in it.
Default Open Modes :
ifstream ios::in
ofstream ios::out
fstream ios::in | ios::out
We can combine the different modes using or symbol | .
Example
ofstream new_file;
new_file.open(“new_file.txt”, ios::out | ios::app );
Here, input mode and append mode are combined which represents the file is opened for
writing and appending the outputs at the end.
As soon as the program terminates, the memory is erased and frees up the memory allocated
and closes the files which are opened.
But it is better to use the close() function to close the opened files after the use of the file.
Using a stream insertion operator << we can write information to a file and using stream
extraction operator >> we can easily read information from a file.
TEMPLATE - Templates are the foundation of generic programming, which involves writing code in a way that is
independent of any particular 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 we can define many different kinds of vectors for example,
vector <int> or vector <string>.
Function Template:The general form of a template function definition is shown here −
template <class type> ret-type func-name(parameter list) {
// body of function}
Here, type is a placeholder name for a data type used by the function. This name can be used within the function definition.
The following is the example of a function template that returns the
maximum of two values −
If we compile and run above code, this would produce the following
result −
Max(i, j): 39
Max(f1, f2): 20.7
Max(s1, s2): World
Class Template
Just as we can define function templates, we can also define
class templates. 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. You can define more than one generic
data type by using a comma-separated list.
Writing to a Binary File
If << is used to write data to a text file. If you had a variable x that contained the value 354 and
you used the statment outfile << x; this would cause the character 3, the character 5, and the
character 4 to be written (in ASCII form) to the file. This is not binary form which would only
require 16-bits. The ofstream class provides a member function named write that allows for
information to be written in binary form to the stream. The prototype of the write function is
ostream& write(void *buffer, streamsize n);
This function causes n bytes to be written from the memory location given by the buffer to the
disk and moves the file pointer ahead n bytes.
Reading from a Binary File
Reading data from a binary file is just like writing it except that the function is now
called read instead of write When reading data from a file there are a couple of new things to
watch out for:It is the responsibility of the programmer to make sure that the buffer is large
enough to hold all the data that is being read. The following code segment would probably
result in a crash unless the size of a integer was 7 bytes (unlikely number):
int main()
{
int x;
ifstream infile;
infile.open("silly.dat", ios::binary | ios::in)
infile.read(&x, 7); // reads 7 bytes into a cell that is either 2 or 4 }
After reading something from the file, the fail() member function should be called to determine
if the operation completed succesfully. In C++, no file operations cause the program to stop. If
an error occurs and you do not check it, then your program will be running unreliably. See a
section further in this document regarding the detection of errors.
EXCEPTION HANDLING-An exception is a problem that arises during the execution of a program.
A C++ exception is a response to an exceptional circumstance that arises while a program is
running, such as an attempt to divide by zero.
Exceptions provide a way to transfer control from one part of a program to another. C++
exception handling is built upon three keywords: try, catch, and throw.
throw − A program throws an exception when a problem shows up. This is done using a throw
keyword.
catch − A program catches an exception with an exception handler at the place in a program
where you want to handle the problem. The catch keyword indicates the catching of an
exception.
try − A try block identifies a block of code for which particular exceptions will be activated. It's
followed by one or more catch blocks.
Assuming a block will raise an exception, a method catches an exception using a combination of
the try and catch keywords. A try/catch block is placed around the code that might generate an
exception. Code within a try/catch block is referred to as protected code, and the syntax for
using try/catch as follows −
try {
// protected code
} catch( ExceptionName e1 ) {
// catch block
} catch( ExceptionName e2 ) {
// catch block
} catch( ExceptionName eN ) {
// catch block
}
Throwing Exceptions
Exceptions can be thrown anywhere within a code block using throw statement. The operand of
the throw statement determines a type for the exception and can be any expression and the
type of the result of the expression determines the type of exception thrown.
Following is an example of throwing an exception when dividing by zero condition occurs −
double division(int a, int b) {
if( b == 0 ) {
throw "Division by zero condition!“; }
return (a/b); }
Catching Exceptions
The catch block following the try block catches any exception. You can specify what type of
exception you want to catch and this is determined by the exception declaration that appears in
parentheses following the keyword catch.
try {
// protected code
} catch( ExceptionName e ) {
// code to handle ExceptionName exception }
Above code will catch an exception of ExceptionName type. If you want to specify that a catch
block should handle any type of exception that is thrown in a try block, you must put an ellipsis,
..., between the parentheses enclosing the exception declaration as follows −
try {
// protected code
} catch(...) {
// code to handle any exception
}
STRINGS
This string is actually a one-dimensional array of characters which is terminated by a null
character '0'. Thus a null-terminated string contains the characters that comprise the string
followed by a null.
The following declaration and initialization create a string consisting of the word "Hello". To hold
the null character at the end of the array, the size of the character array containing the string is
one more than the number of characters in the word "Hello.“
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '0'};
If you follow the rule of array initialization, then you can write the above statement as follows −
char greeting[] = "Hello";
Following is the memory presentation of above defined string in C/C++ −
#include <iostream>
using namespace std;
int main () {
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '0'};
cout << "Greeting message: ";
cout << greeting << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Greeting message: Hello
C++ supports a wide range of functions that manipulate null-terminated strings −
Sr.No Function & Purpose
1 strcpy(s1, s2); Copies string s2 into string s1.
2 strcat(s1, s2); Concatenates string s2 onto the end of string s1.
3 strlen(s1); Returns the length of string s1.
4 strcmp(s1, s2); Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if
s1>s2.
5 strchr(s1, ch); Returns a pointer to the first occurrence of character ch in string s1.
6 strstr(s1, s2); Returns a pointer to the first occurrence of string s2 in string s1.
Following example makes use of few of the above-mentioned functions −
return 0;
}
When the above code is compiled and executed,
it produces result something as follows −
strcpy( str3, str1) : Hello
strcat( str1, str2): HelloWorld
strlen(str1) : 10
THANK YOU!....

More Related Content

Similar to C++ - UNIT_-_V.pptx which contains details about File Concepts

Similar to C++ - UNIT_-_V.pptx which contains details about File Concepts (20)

Srgoc dotnet
Srgoc dotnetSrgoc dotnet
Srgoc dotnet
 
Data file handling
Data file handlingData file handling
Data file handling
 
ExplanationThe files into which we are writing the date area called.pdf
ExplanationThe files into which we are writing the date area called.pdfExplanationThe files into which we are writing the date area called.pdf
ExplanationThe files into which we are writing the date area called.pdf
 
Chapter4.pptx
Chapter4.pptxChapter4.pptx
Chapter4.pptx
 
Input File dalam C++
Input File dalam C++Input File dalam C++
Input File dalam C++
 
C++ppt.pptx
C++ppt.pptxC++ppt.pptx
C++ppt.pptx
 
Linux basics
Linux basicsLinux basics
Linux basics
 
02 fundamentals
02 fundamentals02 fundamentals
02 fundamentals
 
Read write program
Read write programRead write program
Read write program
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
 
Data file handling in c++
Data file handling in c++Data file handling in c++
Data file handling in c++
 
Basic input-output-v.1.1
Basic input-output-v.1.1Basic input-output-v.1.1
Basic input-output-v.1.1
 
PAGE 1Input output for a file tutorialStreams and File IOI.docx
PAGE  1Input output for a file tutorialStreams and File IOI.docxPAGE  1Input output for a file tutorialStreams and File IOI.docx
PAGE 1Input output for a file tutorialStreams and File IOI.docx
 
UNIT 5.pptx
UNIT 5.pptxUNIT 5.pptx
UNIT 5.pptx
 
7 Data File Handling
7 Data File Handling7 Data File Handling
7 Data File Handling
 
VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5
 
Py-Slides-9.ppt
Py-Slides-9.pptPy-Slides-9.ppt
Py-Slides-9.ppt
 
Chapter10
Chapter10Chapter10
Chapter10
 
C++ prgms io file unit 7
C++ prgms io file unit 7C++ prgms io file unit 7
C++ prgms io file unit 7
 

More from ANUSUYA S

Digital Old Question Paper for Reference (Bharathiyar University)
Digital Old Question Paper for Reference (Bharathiyar University)Digital Old Question Paper for Reference (Bharathiyar University)
Digital Old Question Paper for Reference (Bharathiyar University)ANUSUYA S
 
C Old Question Paper for Reference (Bharathiyar University)
C Old Question Paper for Reference (Bharathiyar University)C Old Question Paper for Reference (Bharathiyar University)
C Old Question Paper for Reference (Bharathiyar University)ANUSUYA S
 
C++ Old Question Paper for Reference (Bharathiyar University)
C++ Old Question Paper for Reference (Bharathiyar University)C++ Old Question Paper for Reference (Bharathiyar University)
C++ Old Question Paper for Reference (Bharathiyar University)ANUSUYA S
 
C++ 260 MCQ Question with Answer for all Units
C++ 260 MCQ Question with Answer for all UnitsC++ 260 MCQ Question with Answer for all Units
C++ 260 MCQ Question with Answer for all UnitsANUSUYA S
 
C++ - UNIT_-_II.pptx which used to contain breif description about classes & ...
C++ - UNIT_-_II.pptx which used to contain breif description about classes & ...C++ - UNIT_-_II.pptx which used to contain breif description about classes & ...
C++ - UNIT_-_II.pptx which used to contain breif description about classes & ...ANUSUYA S
 
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...ANUSUYA S
 
C++ - UNIT_-_III.pptx which contains detail description of Operator & Overloa...
C++ - UNIT_-_III.pptx which contains detail description of Operator & Overloa...C++ - UNIT_-_III.pptx which contains detail description of Operator & Overloa...
C++ - UNIT_-_III.pptx which contains detail description of Operator & Overloa...ANUSUYA S
 
C++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about PointersC++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about PointersANUSUYA S
 

More from ANUSUYA S (8)

Digital Old Question Paper for Reference (Bharathiyar University)
Digital Old Question Paper for Reference (Bharathiyar University)Digital Old Question Paper for Reference (Bharathiyar University)
Digital Old Question Paper for Reference (Bharathiyar University)
 
C Old Question Paper for Reference (Bharathiyar University)
C Old Question Paper for Reference (Bharathiyar University)C Old Question Paper for Reference (Bharathiyar University)
C Old Question Paper for Reference (Bharathiyar University)
 
C++ Old Question Paper for Reference (Bharathiyar University)
C++ Old Question Paper for Reference (Bharathiyar University)C++ Old Question Paper for Reference (Bharathiyar University)
C++ Old Question Paper for Reference (Bharathiyar University)
 
C++ 260 MCQ Question with Answer for all Units
C++ 260 MCQ Question with Answer for all UnitsC++ 260 MCQ Question with Answer for all Units
C++ 260 MCQ Question with Answer for all Units
 
C++ - UNIT_-_II.pptx which used to contain breif description about classes & ...
C++ - UNIT_-_II.pptx which used to contain breif description about classes & ...C++ - UNIT_-_II.pptx which used to contain breif description about classes & ...
C++ - UNIT_-_II.pptx which used to contain breif description about classes & ...
 
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
 
C++ - UNIT_-_III.pptx which contains detail description of Operator & Overloa...
C++ - UNIT_-_III.pptx which contains detail description of Operator & Overloa...C++ - UNIT_-_III.pptx which contains detail description of Operator & Overloa...
C++ - UNIT_-_III.pptx which contains detail description of Operator & Overloa...
 
C++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about PointersC++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about Pointers
 

Recently uploaded

Hazratganj ] (Call Girls) in Lucknow - 450+ Call Girl Cash Payment 🧄 89231135...
Hazratganj ] (Call Girls) in Lucknow - 450+ Call Girl Cash Payment 🧄 89231135...Hazratganj ] (Call Girls) in Lucknow - 450+ Call Girl Cash Payment 🧄 89231135...
Hazratganj ] (Call Girls) in Lucknow - 450+ Call Girl Cash Payment 🧄 89231135...akbard9823
 
The First Date by Daniel Johnson (Inspired By True Events)
The First Date by Daniel Johnson (Inspired By True Events)The First Date by Daniel Johnson (Inspired By True Events)
The First Date by Daniel Johnson (Inspired By True Events)thephillipta
 
FULL ENJOY - 9953040155 Call Girls in Gtb Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in Gtb Nagar | DelhiFULL ENJOY - 9953040155 Call Girls in Gtb Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in Gtb Nagar | DelhiMalviyaNagarCallGirl
 
FULL ENJOY - 9953040155 Call Girls in New Ashok Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in New Ashok Nagar | DelhiFULL ENJOY - 9953040155 Call Girls in New Ashok Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in New Ashok Nagar | DelhiMalviyaNagarCallGirl
 
Islamabad Call Girls # 03091665556 # Call Girls in Islamabad | Islamabad Escorts
Islamabad Call Girls # 03091665556 # Call Girls in Islamabad | Islamabad EscortsIslamabad Call Girls # 03091665556 # Call Girls in Islamabad | Islamabad Escorts
Islamabad Call Girls # 03091665556 # Call Girls in Islamabad | Islamabad Escortswdefrd
 
Gomti Nagar & High Profile Call Girls in Lucknow (Adult Only) 8923113531 Esc...
Gomti Nagar & High Profile Call Girls in Lucknow  (Adult Only) 8923113531 Esc...Gomti Nagar & High Profile Call Girls in Lucknow  (Adult Only) 8923113531 Esc...
Gomti Nagar & High Profile Call Girls in Lucknow (Adult Only) 8923113531 Esc...gurkirankumar98700
 
FULL ENJOY - 9953040155 Call Girls in Laxmi Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in Laxmi Nagar | DelhiFULL ENJOY - 9953040155 Call Girls in Laxmi Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in Laxmi Nagar | DelhiMalviyaNagarCallGirl
 
FULL ENJOY - 9953040155 Call Girls in Mahipalpur | Delhi
FULL ENJOY - 9953040155 Call Girls in Mahipalpur | DelhiFULL ENJOY - 9953040155 Call Girls in Mahipalpur | Delhi
FULL ENJOY - 9953040155 Call Girls in Mahipalpur | DelhiMalviyaNagarCallGirl
 
Jeremy Casson - An Architectural and Historical Journey Around Europe
Jeremy Casson - An Architectural and Historical Journey Around EuropeJeremy Casson - An Architectural and Historical Journey Around Europe
Jeremy Casson - An Architectural and Historical Journey Around EuropeJeremy Casson
 
San Jon Motel, Motel/Residence, San Jon NM
San Jon Motel, Motel/Residence, San Jon NMSan Jon Motel, Motel/Residence, San Jon NM
San Jon Motel, Motel/Residence, San Jon NMroute66connected
 
Roadrunner Lodge, Motel/Residence, Tucumcari NM
Roadrunner Lodge, Motel/Residence, Tucumcari NMRoadrunner Lodge, Motel/Residence, Tucumcari NM
Roadrunner Lodge, Motel/Residence, Tucumcari NMroute66connected
 
Call Girl in Bur Dubai O5286O4116 Indian Call Girls in Bur Dubai By VIP Bur D...
Call Girl in Bur Dubai O5286O4116 Indian Call Girls in Bur Dubai By VIP Bur D...Call Girl in Bur Dubai O5286O4116 Indian Call Girls in Bur Dubai By VIP Bur D...
Call Girl in Bur Dubai O5286O4116 Indian Call Girls in Bur Dubai By VIP Bur D...dajasot375
 
exhuma plot and synopsis from the exhuma movie.pptx
exhuma plot and synopsis from the exhuma movie.pptxexhuma plot and synopsis from the exhuma movie.pptx
exhuma plot and synopsis from the exhuma movie.pptxKurikulumPenilaian
 
Patrakarpuram ) Cheap Call Girls In Lucknow (Adult Only) 🧈 8923113531 𓀓 Esco...
Patrakarpuram ) Cheap Call Girls In Lucknow  (Adult Only) 🧈 8923113531 𓀓 Esco...Patrakarpuram ) Cheap Call Girls In Lucknow  (Adult Only) 🧈 8923113531 𓀓 Esco...
Patrakarpuram ) Cheap Call Girls In Lucknow (Adult Only) 🧈 8923113531 𓀓 Esco...akbard9823
 
Turn Lock Take Key Storyboard Daniel Johnson
Turn Lock Take Key Storyboard Daniel JohnsonTurn Lock Take Key Storyboard Daniel Johnson
Turn Lock Take Key Storyboard Daniel Johnsonthephillipta
 
FULL ENJOY - 9953040155 Call Girls in Shaheen Bagh | Delhi
FULL ENJOY - 9953040155 Call Girls in Shaheen Bagh | DelhiFULL ENJOY - 9953040155 Call Girls in Shaheen Bagh | Delhi
FULL ENJOY - 9953040155 Call Girls in Shaheen Bagh | DelhiMalviyaNagarCallGirl
 
FULL ENJOY - 9953040155 Call Girls in Moti Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in Moti Nagar | DelhiFULL ENJOY - 9953040155 Call Girls in Moti Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in Moti Nagar | DelhiMalviyaNagarCallGirl
 
Hazratganj / Call Girl in Lucknow - Phone 🫗 8923113531 ☛ Escorts Service at 6...
Hazratganj / Call Girl in Lucknow - Phone 🫗 8923113531 ☛ Escorts Service at 6...Hazratganj / Call Girl in Lucknow - Phone 🫗 8923113531 ☛ Escorts Service at 6...
Hazratganj / Call Girl in Lucknow - Phone 🫗 8923113531 ☛ Escorts Service at 6...akbard9823
 
Bridge Fight Board by Daniel Johnson dtjohnsonart.com
Bridge Fight Board by Daniel Johnson dtjohnsonart.comBridge Fight Board by Daniel Johnson dtjohnsonart.com
Bridge Fight Board by Daniel Johnson dtjohnsonart.comthephillipta
 

Recently uploaded (20)

Hazratganj ] (Call Girls) in Lucknow - 450+ Call Girl Cash Payment 🧄 89231135...
Hazratganj ] (Call Girls) in Lucknow - 450+ Call Girl Cash Payment 🧄 89231135...Hazratganj ] (Call Girls) in Lucknow - 450+ Call Girl Cash Payment 🧄 89231135...
Hazratganj ] (Call Girls) in Lucknow - 450+ Call Girl Cash Payment 🧄 89231135...
 
The First Date by Daniel Johnson (Inspired By True Events)
The First Date by Daniel Johnson (Inspired By True Events)The First Date by Daniel Johnson (Inspired By True Events)
The First Date by Daniel Johnson (Inspired By True Events)
 
FULL ENJOY - 9953040155 Call Girls in Gtb Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in Gtb Nagar | DelhiFULL ENJOY - 9953040155 Call Girls in Gtb Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in Gtb Nagar | Delhi
 
FULL ENJOY - 9953040155 Call Girls in New Ashok Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in New Ashok Nagar | DelhiFULL ENJOY - 9953040155 Call Girls in New Ashok Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in New Ashok Nagar | Delhi
 
Islamabad Call Girls # 03091665556 # Call Girls in Islamabad | Islamabad Escorts
Islamabad Call Girls # 03091665556 # Call Girls in Islamabad | Islamabad EscortsIslamabad Call Girls # 03091665556 # Call Girls in Islamabad | Islamabad Escorts
Islamabad Call Girls # 03091665556 # Call Girls in Islamabad | Islamabad Escorts
 
Gomti Nagar & High Profile Call Girls in Lucknow (Adult Only) 8923113531 Esc...
Gomti Nagar & High Profile Call Girls in Lucknow  (Adult Only) 8923113531 Esc...Gomti Nagar & High Profile Call Girls in Lucknow  (Adult Only) 8923113531 Esc...
Gomti Nagar & High Profile Call Girls in Lucknow (Adult Only) 8923113531 Esc...
 
FULL ENJOY - 9953040155 Call Girls in Laxmi Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in Laxmi Nagar | DelhiFULL ENJOY - 9953040155 Call Girls in Laxmi Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in Laxmi Nagar | Delhi
 
FULL ENJOY - 9953040155 Call Girls in Mahipalpur | Delhi
FULL ENJOY - 9953040155 Call Girls in Mahipalpur | DelhiFULL ENJOY - 9953040155 Call Girls in Mahipalpur | Delhi
FULL ENJOY - 9953040155 Call Girls in Mahipalpur | Delhi
 
Jeremy Casson - An Architectural and Historical Journey Around Europe
Jeremy Casson - An Architectural and Historical Journey Around EuropeJeremy Casson - An Architectural and Historical Journey Around Europe
Jeremy Casson - An Architectural and Historical Journey Around Europe
 
San Jon Motel, Motel/Residence, San Jon NM
San Jon Motel, Motel/Residence, San Jon NMSan Jon Motel, Motel/Residence, San Jon NM
San Jon Motel, Motel/Residence, San Jon NM
 
Roadrunner Lodge, Motel/Residence, Tucumcari NM
Roadrunner Lodge, Motel/Residence, Tucumcari NMRoadrunner Lodge, Motel/Residence, Tucumcari NM
Roadrunner Lodge, Motel/Residence, Tucumcari NM
 
Call Girl in Bur Dubai O5286O4116 Indian Call Girls in Bur Dubai By VIP Bur D...
Call Girl in Bur Dubai O5286O4116 Indian Call Girls in Bur Dubai By VIP Bur D...Call Girl in Bur Dubai O5286O4116 Indian Call Girls in Bur Dubai By VIP Bur D...
Call Girl in Bur Dubai O5286O4116 Indian Call Girls in Bur Dubai By VIP Bur D...
 
exhuma plot and synopsis from the exhuma movie.pptx
exhuma plot and synopsis from the exhuma movie.pptxexhuma plot and synopsis from the exhuma movie.pptx
exhuma plot and synopsis from the exhuma movie.pptx
 
Patrakarpuram ) Cheap Call Girls In Lucknow (Adult Only) 🧈 8923113531 𓀓 Esco...
Patrakarpuram ) Cheap Call Girls In Lucknow  (Adult Only) 🧈 8923113531 𓀓 Esco...Patrakarpuram ) Cheap Call Girls In Lucknow  (Adult Only) 🧈 8923113531 𓀓 Esco...
Patrakarpuram ) Cheap Call Girls In Lucknow (Adult Only) 🧈 8923113531 𓀓 Esco...
 
Bur Dubai Call Girls # 971504361175 # Call Girls In Bur Dubai || (UAE)
Bur Dubai Call Girls # 971504361175 # Call Girls In Bur Dubai || (UAE)Bur Dubai Call Girls # 971504361175 # Call Girls In Bur Dubai || (UAE)
Bur Dubai Call Girls # 971504361175 # Call Girls In Bur Dubai || (UAE)
 
Turn Lock Take Key Storyboard Daniel Johnson
Turn Lock Take Key Storyboard Daniel JohnsonTurn Lock Take Key Storyboard Daniel Johnson
Turn Lock Take Key Storyboard Daniel Johnson
 
FULL ENJOY - 9953040155 Call Girls in Shaheen Bagh | Delhi
FULL ENJOY - 9953040155 Call Girls in Shaheen Bagh | DelhiFULL ENJOY - 9953040155 Call Girls in Shaheen Bagh | Delhi
FULL ENJOY - 9953040155 Call Girls in Shaheen Bagh | Delhi
 
FULL ENJOY - 9953040155 Call Girls in Moti Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in Moti Nagar | DelhiFULL ENJOY - 9953040155 Call Girls in Moti Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in Moti Nagar | Delhi
 
Hazratganj / Call Girl in Lucknow - Phone 🫗 8923113531 ☛ Escorts Service at 6...
Hazratganj / Call Girl in Lucknow - Phone 🫗 8923113531 ☛ Escorts Service at 6...Hazratganj / Call Girl in Lucknow - Phone 🫗 8923113531 ☛ Escorts Service at 6...
Hazratganj / Call Girl in Lucknow - Phone 🫗 8923113531 ☛ Escorts Service at 6...
 
Bridge Fight Board by Daniel Johnson dtjohnsonart.com
Bridge Fight Board by Daniel Johnson dtjohnsonart.comBridge Fight Board by Daniel Johnson dtjohnsonart.com
Bridge Fight Board by Daniel Johnson dtjohnsonart.com
 

C++ - UNIT_-_V.pptx which contains details about File Concepts

  • 1. UNIT – V FILES File Handling In C++ Files are used to store data in a storage device permanently. File handling provides a mechanism to store the output of a program in a file and to perform various operations on it. A stream is an abstraction that represents a device on which operations of input and output are performed. A stream can be represented as a source or destination of characters of indefinite length depending on its usage. In C++ we have a set of file handling methods. These include ifstream, ofstream, and fstream. These classes are derived from fstrembase and from the corresponding iostream class. These classes, designed to manage the disk files, are declared in fstream and therefore we must include fstream and therefore we must include this file in any program that uses files. In C++, files are mainly dealt by using three classes fstream, ifstream, ofstream. ofstream: This Stream class signifies the output file stream and is applied to create files for writing information to files ifstream: This Stream class signifies the input file stream and is applied for reading information from files fstream: This Stream class can be used for both read and write from/to files.
  • 2. C++ provides us with the following operations in File Handling: - MODES Creating a file: open(), Reading data: read(), Writing new data: write(), Closing a file: close() Opening a File Generally, the first operation performed on an object of one of these classes is to associate it to a real file. This procedure is known to open a file. We can open a file using any one of the following methods: 1. First is bypassing the file name in constructor at the time of object creation. 2. Second is using the open() function. To open a file use open() function Syntax - void open(const char* file_name,ios::openmode mode); Here, the first argument of the open function defines the name and format of the file with the address of the file. The second argument represents the mode in which the file has to be opened. The following modes are used as per the requirements. Modes Description In - Opens the file to read(default for ifstream) Out-Opens the file to write(default for ofstream) Binary-Opens the file in binary mode App-Opens the file and appends all the outputs at the end Ate-Opens the file and moves the control to the end of the file Trunc-Removes the data in the existing file Nocreate-Opens the file only if it already exists Noreplace-Opens the file only if it does not already exist
  • 3. Example fstream new_file; new_file.open(“newfile.txt”, ios::out); In the above example, new_file is an object of type fstream, as we know fstream is a class so we need to create an object of this class to use its member functions. So we create new_file object and call open() function. Here we use out mode that allows us to open the file to write in it. Default Open Modes : ifstream ios::in ofstream ios::out fstream ios::in | ios::out We can combine the different modes using or symbol | . Example ofstream new_file; new_file.open(“new_file.txt”, ios::out | ios::app ); Here, input mode and append mode are combined which represents the file is opened for writing and appending the outputs at the end. As soon as the program terminates, the memory is erased and frees up the memory allocated and closes the files which are opened. But it is better to use the close() function to close the opened files after the use of the file. Using a stream insertion operator << we can write information to a file and using stream extraction operator >> we can easily read information from a file.
  • 4. TEMPLATE - Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular 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 we can define many different kinds of vectors for example, vector <int> or vector <string>. Function Template:The general form of a template function definition is shown here − template <class type> ret-type func-name(parameter list) { // body of function} Here, type is a placeholder name for a data type used by the function. This name can be used within the function definition. The following is the example of a function template that returns the maximum of two values − If we compile and run above code, this would produce the following result − Max(i, j): 39 Max(f1, f2): 20.7 Max(s1, s2): World Class Template Just as we can define function templates, we can also define class templates. 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. You can define more than one generic data type by using a comma-separated list.
  • 5. Writing to a Binary File If << is used to write data to a text file. If you had a variable x that contained the value 354 and you used the statment outfile << x; this would cause the character 3, the character 5, and the character 4 to be written (in ASCII form) to the file. This is not binary form which would only require 16-bits. The ofstream class provides a member function named write that allows for information to be written in binary form to the stream. The prototype of the write function is ostream& write(void *buffer, streamsize n); This function causes n bytes to be written from the memory location given by the buffer to the disk and moves the file pointer ahead n bytes. Reading from a Binary File Reading data from a binary file is just like writing it except that the function is now called read instead of write When reading data from a file there are a couple of new things to watch out for:It is the responsibility of the programmer to make sure that the buffer is large enough to hold all the data that is being read. The following code segment would probably result in a crash unless the size of a integer was 7 bytes (unlikely number): int main() { int x; ifstream infile; infile.open("silly.dat", ios::binary | ios::in) infile.read(&x, 7); // reads 7 bytes into a cell that is either 2 or 4 } After reading something from the file, the fail() member function should be called to determine if the operation completed succesfully. In C++, no file operations cause the program to stop. If an error occurs and you do not check it, then your program will be running unreliably. See a section further in this document regarding the detection of errors.
  • 6. EXCEPTION HANDLING-An exception is a problem that arises during the execution of a program. A C++ exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero. Exceptions provide a way to transfer control from one part of a program to another. C++ exception handling is built upon three keywords: try, catch, and throw. throw − A program throws an exception when a problem shows up. This is done using a throw keyword. catch − A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception. try − A try block identifies a block of code for which particular exceptions will be activated. It's followed by one or more catch blocks. Assuming a block will raise an exception, a method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch as follows − try { // protected code } catch( ExceptionName e1 ) { // catch block } catch( ExceptionName e2 ) { // catch block } catch( ExceptionName eN ) { // catch block }
  • 7. Throwing Exceptions Exceptions can be thrown anywhere within a code block using throw statement. The operand of the throw statement determines a type for the exception and can be any expression and the type of the result of the expression determines the type of exception thrown. Following is an example of throwing an exception when dividing by zero condition occurs − double division(int a, int b) { if( b == 0 ) { throw "Division by zero condition!“; } return (a/b); } Catching Exceptions The catch block following the try block catches any exception. You can specify what type of exception you want to catch and this is determined by the exception declaration that appears in parentheses following the keyword catch. try { // protected code } catch( ExceptionName e ) { // code to handle ExceptionName exception } Above code will catch an exception of ExceptionName type. If you want to specify that a catch block should handle any type of exception that is thrown in a try block, you must put an ellipsis, ..., between the parentheses enclosing the exception declaration as follows − try { // protected code } catch(...) { // code to handle any exception }
  • 8. STRINGS This string is actually a one-dimensional array of characters which is terminated by a null character '0'. Thus a null-terminated string contains the characters that comprise the string followed by a null. The following declaration and initialization create a string consisting of the word "Hello". To hold the null character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word "Hello.“ char greeting[6] = {'H', 'e', 'l', 'l', 'o', '0'}; If you follow the rule of array initialization, then you can write the above statement as follows − char greeting[] = "Hello"; Following is the memory presentation of above defined string in C/C++ − #include <iostream> using namespace std; int main () { char greeting[6] = {'H', 'e', 'l', 'l', 'o', '0'}; cout << "Greeting message: "; cout << greeting << endl; return 0; } When the above code is compiled and executed, it produces the following result − Greeting message: Hello C++ supports a wide range of functions that manipulate null-terminated strings −
  • 9. Sr.No Function & Purpose 1 strcpy(s1, s2); Copies string s2 into string s1. 2 strcat(s1, s2); Concatenates string s2 onto the end of string s1. 3 strlen(s1); Returns the length of string s1. 4 strcmp(s1, s2); Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2. 5 strchr(s1, ch); Returns a pointer to the first occurrence of character ch in string s1. 6 strstr(s1, s2); Returns a pointer to the first occurrence of string s2 in string s1. Following example makes use of few of the above-mentioned functions − return 0; } When the above code is compiled and executed, it produces result something as follows − strcpy( str3, str1) : Hello strcat( str1, str2): HelloWorld strlen(str1) : 10