SlideShare a Scribd company logo
File handling in C++
BCA Sem III
K.I.R.A.S
Using Input/Output Files
 Files in C++ are interpreted as a sequence of bytes stored on some
storage media.
 The data of a file is stored in either readable form or in binary code
called as text file or binary file.
 The flow of data from any source to a sink is called as a stream
 Computer programs are associated to work with files as it helps in
storing data & information permanently.
 File - itself a bunch of bytes stored on some storage devices.
 In C++ this is achieved through a component header file called
fstream.h
 The I/O library manages two aspects- as interface and for transfer
of data.
 The library predefine a set of operations for all file related handling
through certain classes.
Using Input/Output Files
A computer fileA computer file
 is stored on a secondary storage device (e.g.,is stored on a secondary storage device (e.g.,
disk);disk);
 is permanent;is permanent;
 can be used to provide input data to acan be used to provide input data to a
program or receive output data from aprogram or receive output data from a
program, or both;program, or both;
 must be opened before it is used.must be opened before it is used.
General File I/O Steps
Declare a file name variable
 Associate the file name variable with the
disk file name
 Open the file
 Use the file
 Close the file
Using Input/Output Files
 Streams act as an interface between files and programs. In C++ . A
stream is used to refer to the flow of data from a particular device to
the program’s variablesThe device here refers to files, keyboard,
console, memory arrays. In C++ these streams are treated as
objects to support consistent access interface.
 They represent as a sequence of bytes and deals with the flow of
data.
 Every stream is associated with a class having member functions
and operations for a particular kind of data flow.
 File -> Program ( Input stream) - reads
 Program -> File (Output stream) – write
 All designed into fstream.h and hence needs to be included in all file
handling programs.
 Diagrammatically as shown in next slide
Using Input/Output Files
 streamstream - a sequence of characters- a sequence of characters
 interactive (iostream)interactive (iostream)
•• cincin - input stream associated with- input stream associated with keyboard.keyboard.
•• coutcout - output stream associated with- output stream associated with display.display.
 file (fstream)file (fstream)
•• ifstreamifstream - defines new input stream (normally- defines new input stream (normally
associated with a file).associated with a file).
•• ofstreamofstream - defines new output stream (normally- defines new output stream (normally
associated with a file).associated with a file).
• Stream of bytes to do input and output to different devices.
• Stream is the basic concepts which can be attached to files, strings, console and
other devices.
• User can also create their own stream to cater specific device or user defined
Streams
 A stream is a series of bytes, which act either as a
source from which data can be extracted or as a
destination to which the output can be sent. Streams
resemble the producer and consumer model
 The producer produces the items to be consumed by the
consumer. The producer and the consumers are
connected by the C++ operators >> or <<. For instance ,
the keyboard exhibits the nature of only a
producer,printer or monitor screen exhibit the nature of
only a consumer. Whereas , a file stored on the disk ,
can behave as a producer or consumer, depending upon
the operation initiated on it.
Predefined console streams
C++ contains several predefined streams that are
opened automatically when the execution of a
program starts.
1) cin :standard input (usually keyboard) corresponding
to stdio in C
2) cout :standard output (usually screen) corresponding
to stdout in C
3) cerr :standard error output (usually screen)
corresponding to stderr in C
4) clog : A fully buffered version of cerr (No C
equivalent)
Why to use Files
 Convenient way to deal large quantities of data.
 Store data permanently (until file is deleted).
 Avoid typing data into program multiple times.
 Share data between programs.
 We need to know:
 how to "connect" file to program
 how to tell the program to read data
 how to tell the program to write data
 error checking and handling EOF
Classes for Stream I/O in C++
ios is the base class.ios is the base class.
istream and ostream inherit fromistream and ostream inherit from
iosios
ifstream inherits from istreamifstream inherits from istream
(and ios)(and ios)
ofstream inherits from ostreamofstream inherits from ostream
(and ios)(and ios)
iostream inherits from istreamiostream inherits from istream
and ostream (& ios)and ostream (& ios)
fstream inherits from ifstream,fstream inherits from ifstream,
iostream, and ofstreamiostream, and ofstream
When working with files in C++, the
following classes can be used:
ofstream – writing to a file
ifstream – reading for a file
fstream – reading / writing
When ever we include <iostream.h>, an
ostream object, is automatically defined –
this object is cout.
ofstream inherits from the class ostream
(standard output class).
ostream overloaded the operator >> for
standard output.…thus an ofstream object
can use methods and operators defined in
ostream.
File Modes
Name Description
ios::in Open file to read
ios::out Open file to write
ios::app All the date you write, is put at the end of the file.
It calls ios::out
ios::ate All the date you write, is put at the end of the file.
It does not call ios::out
ios::trunc Deletes all previous content in the file. (empties
the file)
ios::nocreate If the file does not exist, opening it with the open()
function gets impossible.
ios::noreplace If the file exists, trying to open it with the open()
function, returns an error.
ios::binary Opens the file in binary mode.
File Modes
 Opening a file in ios::out mode also opens it in the
ios::trunc mode by default. That is, if the file already
exists, it is truncated
 Both ios::app and ios::ate set the pointers to the end of
file, but they differ in terms of the types of operations
permitted on a file. The ios::app allows to add data from
end of file, whereas ios::ate mode allows to add or
modify the existing data anywhere in the file. In both the
cases the file is created if it is non existent.
 The mode ios::app can be used only with output files
 The stream classes ifstream and ofstream open files in
read and write modes by default.
File pointers
 Each file has two associated pointers known as the file pointers.
One of them is called the input pointer or get pointer.
The get pointer specifies a location from which the current reading
operation is initiated
Other is called the output pointer or put pointer.
The put pointer specifies a location from where the current writing
operation is initiated
We can use these pointers to move through the files while reading
or writing.
The input pointer is used for reading the contents of a given file
location and the output pointer is used for writing to a given file
location.
Functions for manipulation of file pointers
seekg() Moves get pointer (input) to a specified location.
seekp() Moves put pointer (output) to a specified location.
tellg() Gives the current position of the get pointer.
tellp() Gives the current position of the put pointer.
File pointers
infile.seekg(10);
Moves the file pointer to the byte number 10.
The bytes in a file are numbered beginning from zero. Thus, the pointer will
be pointing to the 11th byte in the file.
Specifying the offset :
The seek functions seekg() and seekp() can also be used with two
arguments as follows:
seekg(offset, refposition);
seekp(offset, refposition);
The parameter offset represents the number of bytes the file pointer to
be moved from the location specified by the parameter refposition.
The refposition takes one of the following these constant defined in
the ios class.
ios::beg start of the file
ios::cur current position of the pointer
ios::end end of the file.
File Open Mode
#include <fstream>
int main(void)
{
ofstream outFile("file1.txt", ios::out);
outFile << "That's new!n";
outFile.close();
Return 0;
}
If you want to set more than one open mode, just use the
OR operator- |. This way:
ios::ate | ios::binary
Dealing with Binary files
Functions for binary file handlingFunctions for binary file handling
get():get(): read a byte and point to the next byte to readread a byte and point to the next byte to read
put():put(): write a byte and point to the next location forwrite a byte and point to the next location for
writewrite
read():read(): block readingblock reading
write():write(): block writingblock writing
flush():flush():Save data from the buffer to the output file.Save data from the buffer to the output file.
Binary File I/O Examples
//Example 1: Using get() and put()
#include <iostream>
#include <fstream>
void main()
{
fstream File("test_file",ios::out | ios::in | ios::binary);
char ch;
ch='o';
File.put(ch); //put the content of ch to the file
File.seekg(ios::beg); //go to the beginning of the file
File.get(ch); //read one character
cout << ch << endl; //display it
File.close();
}
File I/O Example: Writing
#include <fstream>#include <fstream>
using namespace std;using namespace std;
int main(void)int main(void)
{{
ofstream outFile(“fout.txt");ofstream outFile(“fout.txt");
outFile << "Hello World!";outFile << "Hello World!";
outFile.close();outFile.close();
return 0;return 0;
}}
File I/O Example: Reading
#include <iostream>#include <iostream>
#include <fstream>#include <fstream>
int main(void)int main(void)
{{
ifstream openFile(“data.txt"); //open a text file data.txtifstream openFile(“data.txt"); //open a text file data.txt
char ch;char ch;
while(!OpenFile.eof())while(!OpenFile.eof())
{{
OpenFile.get(ch);OpenFile.get(ch);
cout << ch;cout << ch;
}}
OpenFile.close();OpenFile.close();
return 0;return 0;
}}
File I/O Example: Reading
#include <iostream>#include <iostream>
#include <fstream>#include <fstream>
#include <string>#include <string>
int main(void)int main(void)
{{
ifstream openFile(“data.txt"); //open a text file data.txtifstream openFile(“data.txt"); //open a text file data.txt
string line;string line;
if(openFile.is_open()){ //if(openFile.is_open()){ //
while(!openFile.eof()){while(!openFile.eof()){
getline(openFile,line);//read a line from data.txt and put it in a stringgetline(openFile,line);//read a line from data.txt and put it in a string
cout << line;cout << line;
}}
else{else{
cout<<“File does not exist!”<<endl;cout<<“File does not exist!”<<endl;
exit(1);}exit(1);}
}}
openFile.close();openFile.close();
return 0;return 0;
}}
To access file handling routines:
#include <fstream.h>
2: To declare variables that can be used to access file:
ifstream in_stream;
ofstream out_stream;
3: To connect your program's variable (its internal name) to
an external file (i.e., on the Unix file system):
in_stream.open("infile.dat");
out_stream.open("outfile.dat");
4: To see if the file opened successfully:
if (in_stream.fail())
{ cout << "Input file open failedn";
exit(1); // requires <stdlib.h>}
To get data from a file (one option), must declare a variable
to hold the data and then read it using the extraction
operator:
int num;
in_stream >> num;
[Compare: cin >> num;]
6: To put data into a file, use insertion operator:
out_stream << num;
[Compare: cout << num;]
NOTE: Streams are sequential – data is read and written in
order – generally can't back up.
7: When done with the file:
in_stream.close();
out_stream.close();
Reading /Writing from/to Binary Files
 To write n bytes:
 write (const unsigned char* buffer, int n);
 To read n bytes (to a pre-allocated buffer):
 read (unsighed char* buffer, int num)
#include <fstream.h>
main()
{
int array[] = {10,23,3,7,9,11,253};
ofstream OutBinaryFile("my_b_file.txt“, ios::out |
ios::binary);
OutBinaryFile.write((char*) array, sizeof(array));
OutBinaryFile.close();
}
C++ has some low-level facilities for character I/O.C++ has some low-level facilities for character I/O.
char next1, next2, next3;char next1, next2, next3;
cin.get(next1);cin.get(next1);
Gets the next character from the keyboard. Does not skip overGets the next character from the keyboard. Does not skip over
blanks or newline (n). Can check for newline (next == 'n')blanks or newline (n). Can check for newline (next == 'n')
Example:Example:
 cin.get(next1);cin.get(next1);
 cin.get(next2);cin.get(next2);
 cin.get(next3);cin.get(next3);
Predefined character functions must #include <ctype.h> and can be
used to
 convert between upper and lower case
 test whether in upper or lower case
 test whether alphabetic character or digit
 test for space
Reading /Writing from/to Textual Files
#include <fstream.h>
main()
{
// Writing to file
ofstream OutFile("my_file.txt");
OutFile<<"Hello "<<5<<endl;
OutFile.close();
int number;
char dummy[15];
// Reading from file
ifstream InFile("my_file.txt");
InFile>>dummy>>number;
InFile.seekg(0);
InFile.getline(dummy,sizeof(dummy));
InFile.close();
}
To write:
put() – writing single character
<< operator – writing an object
To read:
get() – reading a single character of a
buffer
getline() – reading a single line
>> operator – reading a object
Binary file operations
In connection with a binary file, the file mode
must contain the ios::binary mode along
with other mode(s)
To read & write a or on to a binary file,
as the case may be blocks of data are accessed
through
the use of C++ read() and write() respectively.
Handling binary data
#include <fstream>
using namespace std;
int main(){
ifstream in(“binfile.dat”);
ofstream out(“out.dat”);
if(!in || !out) { // return}
unsigned int buf[1024];
while(!in){
in.read(buf, sizeof(unsigned
int)*1024);
out.write(buf, sizeof(unsigned
int)*1024);
}

More Related Content

What's hot

Strings in c
Strings in cStrings in c
Strings in c
vampugani
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
Nadeesha Thilakarathne
 
File in c
File in cFile in c
File in c
Prabhu Govind
 
Java String Handling
Java String HandlingJava String Handling
Java String Handling
Infoviaan Technologies
 
Loader
LoaderLoader
Loader
nikhilshrama
 
Introduction to pointers and memory management in C
Introduction to pointers and memory management in CIntroduction to pointers and memory management in C
Introduction to pointers and memory management in C
Uri Dekel
 
python.pptx
python.pptxpython.pptx
python.pptx
SabthamiS1
 
Files in php
Files in phpFiles in php
Files in php
sana mateen
 
Python - Lecture 11
Python - Lecture 11Python - Lecture 11
Python - Lecture 11
Ravi Kiran Khareedi
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++Tech_MX
 
File in C language
File in C languageFile in C language
File in C language
Manash Kumar Mondal
 
Exception handling in c++
Exception handling in c++Exception handling in c++
Exception handling in c++
imran khan
 
Files and streams
Files and streamsFiles and streams
Files and streams
Pranali Chaudhari
 
Strings in C language
Strings in C languageStrings in C language
Strings in C language
P M Patil
 
Python OOPs
Python OOPsPython OOPs
Python OOPs
Binay Kumar Ray
 
Presentation1
Presentation1Presentation1
Presentation1
Anul Chaudhary
 
Exception handling c++
Exception handling c++Exception handling c++
Exception handling c++
Jayant Dalvi
 

What's hot (20)

Strings in c
Strings in cStrings in c
Strings in c
 
File Pointers
File PointersFile Pointers
File Pointers
 
File Handling in C++
File Handling in C++File Handling in C++
File Handling in C++
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
File in c
File in cFile in c
File in c
 
C fundamental
C fundamentalC fundamental
C fundamental
 
Java String Handling
Java String HandlingJava String Handling
Java String Handling
 
Loader
LoaderLoader
Loader
 
Introduction to pointers and memory management in C
Introduction to pointers and memory management in CIntroduction to pointers and memory management in C
Introduction to pointers and memory management in C
 
python.pptx
python.pptxpython.pptx
python.pptx
 
Files in php
Files in phpFiles in php
Files in php
 
Python - Lecture 11
Python - Lecture 11Python - Lecture 11
Python - Lecture 11
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++
 
File in C language
File in C languageFile in C language
File in C language
 
Exception handling in c++
Exception handling in c++Exception handling in c++
Exception handling in c++
 
Files and streams
Files and streamsFiles and streams
Files and streams
 
Strings in C language
Strings in C languageStrings in C language
Strings in C language
 
Python OOPs
Python OOPsPython OOPs
Python OOPs
 
Presentation1
Presentation1Presentation1
Presentation1
 
Exception handling c++
Exception handling c++Exception handling c++
Exception handling c++
 

Viewers also liked

basics of file handling
basics of file handlingbasics of file handling
basics of file handlingpinkpreet_kaur
 
File handling
File handlingFile handling
File handling
Nilesh Dalvi
 
File in cpp 2016
File in cpp 2016 File in cpp 2016
File in cpp 2016
Dr .Ahmed Tawwab
 
Pointers
PointersPointers
Pointers
sanya6900
 
Handling computer files
Handling computer filesHandling computer files
Handling computer files
Samuel Igbanogu
 
Input and output in C++
Input and output in C++Input and output in C++
Input and output in C++
Nilesh Dalvi
 
Data file handling in c++
Data file handling in c++Data file handling in c++
Data file handling in c++
Vineeta Garg
 
14 file handling
14 file handling14 file handling
14 file handlingAPU
 
Files in c++
Files in c++Files in c++
Files in c++
Selvin Josy Bai Somu
 
file handling c++
file handling c++file handling c++
file handling c++Guddu Spy
 

Viewers also liked (11)

basics of file handling
basics of file handlingbasics of file handling
basics of file handling
 
File handling
File handlingFile handling
File handling
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
 
File in cpp 2016
File in cpp 2016 File in cpp 2016
File in cpp 2016
 
Pointers
PointersPointers
Pointers
 
Handling computer files
Handling computer filesHandling computer files
Handling computer files
 
Input and output in C++
Input and output in C++Input and output in C++
Input and output in C++
 
Data file handling in c++
Data file handling in c++Data file handling in c++
Data file handling in c++
 
14 file handling
14 file handling14 file handling
14 file handling
 
Files in c++
Files in c++Files in c++
Files in c++
 
file handling c++
file handling c++file handling c++
file handling c++
 

Similar to File handling in_c

new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
AzanMehdi
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handlingpinkpreet_kaur
 
Basics of files and its functions with example
Basics of files and its functions with exampleBasics of files and its functions with example
Basics of files and its functions with example
Sunil Patel
 
Files in C++.pdf is the notes of cpp for reference
Files in C++.pdf is the notes of cpp for referenceFiles in C++.pdf is the notes of cpp for reference
Files in C++.pdf is the notes of cpp for reference
anuvayalil5525
 
Filehandlinging cp2
Filehandlinging cp2Filehandlinging cp2
Filehandlinging cp2
Tanmay Baranwal
 
File management in C++
File management in C++File management in C++
File management in C++
apoorvaverma33
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++
Shyam Gupta
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01
Rex Joe
 
Data file handling
Data file handlingData file handling
Data file handling
Prof. Dr. K. Adisesha
 
File Handling
File HandlingFile Handling
File Handling
TusharBatra27
 
Cpp file-handling
Cpp file-handlingCpp file-handling
Cpp file-handling
JiaahRajpout123
 
Filepointers1 1215104829397318-9
Filepointers1 1215104829397318-9Filepointers1 1215104829397318-9
Filepointers1 1215104829397318-9
AbdulghafarStanikzai
 
Chapter28 data-file-handling
Chapter28 data-file-handlingChapter28 data-file-handling
Chapter28 data-file-handlingDeepak Singh
 
7 Data File Handling
7 Data File Handling7 Data File Handling
7 Data File Handling
Praveen M Jigajinni
 
Chapter4.pptx
Chapter4.pptxChapter4.pptx
Chapter4.pptx
WondimuBantihun1
 
Data file handling
Data file handlingData file handling
Data file handlingTAlha MAlik
 
C library for input output operations.cstdio.(stdio.h)
C library for input output operations.cstdio.(stdio.h)C library for input output operations.cstdio.(stdio.h)
C library for input output operations.cstdio.(stdio.h)
leonard horobet-stoian
 
Filehadnling
FilehadnlingFilehadnling
Filehadnling
Khushal Mehta
 
Managing,working with files
Managing,working with filesManaging,working with files
Managing,working with files
kirupasuchi1996
 

Similar to File handling in_c (20)

new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
 
Basics of files and its functions with example
Basics of files and its functions with exampleBasics of files and its functions with example
Basics of files and its functions with example
 
Files in C++.pdf is the notes of cpp for reference
Files in C++.pdf is the notes of cpp for referenceFiles in C++.pdf is the notes of cpp for reference
Files in C++.pdf is the notes of cpp for reference
 
Filehandlinging cp2
Filehandlinging cp2Filehandlinging cp2
Filehandlinging cp2
 
File management in C++
File management in C++File management in C++
File management in C++
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01
 
Data file handling
Data file handlingData file handling
Data file handling
 
File Handling
File HandlingFile Handling
File Handling
 
cpp-file-handling
cpp-file-handlingcpp-file-handling
cpp-file-handling
 
Cpp file-handling
Cpp file-handlingCpp file-handling
Cpp file-handling
 
Filepointers1 1215104829397318-9
Filepointers1 1215104829397318-9Filepointers1 1215104829397318-9
Filepointers1 1215104829397318-9
 
Chapter28 data-file-handling
Chapter28 data-file-handlingChapter28 data-file-handling
Chapter28 data-file-handling
 
7 Data File Handling
7 Data File Handling7 Data File Handling
7 Data File Handling
 
Chapter4.pptx
Chapter4.pptxChapter4.pptx
Chapter4.pptx
 
Data file handling
Data file handlingData file handling
Data file handling
 
C library for input output operations.cstdio.(stdio.h)
C library for input output operations.cstdio.(stdio.h)C library for input output operations.cstdio.(stdio.h)
C library for input output operations.cstdio.(stdio.h)
 
Filehadnling
FilehadnlingFilehadnling
Filehadnling
 
Managing,working with files
Managing,working with filesManaging,working with files
Managing,working with files
 

More from sanya6900

.Net framework
.Net framework.Net framework
.Net framework
sanya6900
 
INTRODUCTION TO IIS
INTRODUCTION TO IISINTRODUCTION TO IIS
INTRODUCTION TO IIS
sanya6900
 
INTRODUCTION TO IIS
INTRODUCTION TO IISINTRODUCTION TO IIS
INTRODUCTION TO IISsanya6900
 
Type conversions
Type conversionsType conversions
Type conversions
sanya6900
 
Templates exception handling
Templates exception handlingTemplates exception handling
Templates exception handling
sanya6900
 
operators and expressions in c++
 operators and expressions in c++ operators and expressions in c++
operators and expressions in c++
sanya6900
 
Memory allocation
Memory allocationMemory allocation
Memory allocation
sanya6900
 
Ch7
Ch7Ch7
Cpphtp4 ppt 03
Cpphtp4 ppt 03Cpphtp4 ppt 03
Cpphtp4 ppt 03
sanya6900
 
Inheritance (1)
Inheritance (1)Inheritance (1)
Inheritance (1)
sanya6900
 
C++ overloading
C++ overloadingC++ overloading
C++ overloading
sanya6900
 
C cpluplus 2
C cpluplus 2C cpluplus 2
C cpluplus 2
sanya6900
 

More from sanya6900 (12)

.Net framework
.Net framework.Net framework
.Net framework
 
INTRODUCTION TO IIS
INTRODUCTION TO IISINTRODUCTION TO IIS
INTRODUCTION TO IIS
 
INTRODUCTION TO IIS
INTRODUCTION TO IISINTRODUCTION TO IIS
INTRODUCTION TO IIS
 
Type conversions
Type conversionsType conversions
Type conversions
 
Templates exception handling
Templates exception handlingTemplates exception handling
Templates exception handling
 
operators and expressions in c++
 operators and expressions in c++ operators and expressions in c++
operators and expressions in c++
 
Memory allocation
Memory allocationMemory allocation
Memory allocation
 
Ch7
Ch7Ch7
Ch7
 
Cpphtp4 ppt 03
Cpphtp4 ppt 03Cpphtp4 ppt 03
Cpphtp4 ppt 03
 
Inheritance (1)
Inheritance (1)Inheritance (1)
Inheritance (1)
 
C++ overloading
C++ overloadingC++ overloading
C++ overloading
 
C cpluplus 2
C cpluplus 2C cpluplus 2
C cpluplus 2
 

Recently uploaded

NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
Amil Baba Dawood bangali
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation & Control
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
thanhdowork
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
Neometrix_Engineering_Pvt_Ltd
 
AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
BrazilAccount1
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
FluxPrime1
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
JoytuBarua2
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
Osamah Alsalih
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
R&R Consult
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
Robbie Edward Sayers
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Dr.Costas Sachpazis
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
MdTanvirMahtab2
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
AhmedHussein950959
 
Hierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power SystemHierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power System
Kerry Sado
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
SamSarthak3
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
ongomchris
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
Vijay Dialani, PhD
 

Recently uploaded (20)

NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
 
AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
 
Hierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power SystemHierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power System
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
 

File handling in_c

  • 1. File handling in C++ BCA Sem III K.I.R.A.S
  • 2. Using Input/Output Files  Files in C++ are interpreted as a sequence of bytes stored on some storage media.  The data of a file is stored in either readable form or in binary code called as text file or binary file.  The flow of data from any source to a sink is called as a stream  Computer programs are associated to work with files as it helps in storing data & information permanently.  File - itself a bunch of bytes stored on some storage devices.  In C++ this is achieved through a component header file called fstream.h  The I/O library manages two aspects- as interface and for transfer of data.  The library predefine a set of operations for all file related handling through certain classes.
  • 3. Using Input/Output Files A computer fileA computer file  is stored on a secondary storage device (e.g.,is stored on a secondary storage device (e.g., disk);disk);  is permanent;is permanent;  can be used to provide input data to acan be used to provide input data to a program or receive output data from aprogram or receive output data from a program, or both;program, or both;  must be opened before it is used.must be opened before it is used.
  • 4. General File I/O Steps Declare a file name variable  Associate the file name variable with the disk file name  Open the file  Use the file  Close the file
  • 5. Using Input/Output Files  Streams act as an interface between files and programs. In C++ . A stream is used to refer to the flow of data from a particular device to the program’s variablesThe device here refers to files, keyboard, console, memory arrays. In C++ these streams are treated as objects to support consistent access interface.  They represent as a sequence of bytes and deals with the flow of data.  Every stream is associated with a class having member functions and operations for a particular kind of data flow.  File -> Program ( Input stream) - reads  Program -> File (Output stream) – write  All designed into fstream.h and hence needs to be included in all file handling programs.  Diagrammatically as shown in next slide
  • 6.
  • 7. Using Input/Output Files  streamstream - a sequence of characters- a sequence of characters  interactive (iostream)interactive (iostream) •• cincin - input stream associated with- input stream associated with keyboard.keyboard. •• coutcout - output stream associated with- output stream associated with display.display.  file (fstream)file (fstream) •• ifstreamifstream - defines new input stream (normally- defines new input stream (normally associated with a file).associated with a file). •• ofstreamofstream - defines new output stream (normally- defines new output stream (normally associated with a file).associated with a file). • Stream of bytes to do input and output to different devices. • Stream is the basic concepts which can be attached to files, strings, console and other devices. • User can also create their own stream to cater specific device or user defined
  • 8. Streams  A stream is a series of bytes, which act either as a source from which data can be extracted or as a destination to which the output can be sent. Streams resemble the producer and consumer model  The producer produces the items to be consumed by the consumer. The producer and the consumers are connected by the C++ operators >> or <<. For instance , the keyboard exhibits the nature of only a producer,printer or monitor screen exhibit the nature of only a consumer. Whereas , a file stored on the disk , can behave as a producer or consumer, depending upon the operation initiated on it.
  • 9. Predefined console streams C++ contains several predefined streams that are opened automatically when the execution of a program starts. 1) cin :standard input (usually keyboard) corresponding to stdio in C 2) cout :standard output (usually screen) corresponding to stdout in C 3) cerr :standard error output (usually screen) corresponding to stderr in C 4) clog : A fully buffered version of cerr (No C equivalent)
  • 10. Why to use Files  Convenient way to deal large quantities of data.  Store data permanently (until file is deleted).  Avoid typing data into program multiple times.  Share data between programs.  We need to know:  how to "connect" file to program  how to tell the program to read data  how to tell the program to write data  error checking and handling EOF
  • 11. Classes for Stream I/O in C++ ios is the base class.ios is the base class. istream and ostream inherit fromistream and ostream inherit from iosios ifstream inherits from istreamifstream inherits from istream (and ios)(and ios) ofstream inherits from ostreamofstream inherits from ostream (and ios)(and ios) iostream inherits from istreamiostream inherits from istream and ostream (& ios)and ostream (& ios) fstream inherits from ifstream,fstream inherits from ifstream, iostream, and ofstreamiostream, and ofstream When working with files in C++, the following classes can be used: ofstream – writing to a file ifstream – reading for a file fstream – reading / writing When ever we include <iostream.h>, an ostream object, is automatically defined – this object is cout. ofstream inherits from the class ostream (standard output class). ostream overloaded the operator >> for standard output.…thus an ofstream object can use methods and operators defined in ostream.
  • 12.
  • 13. File Modes Name Description ios::in Open file to read ios::out Open file to write ios::app All the date you write, is put at the end of the file. It calls ios::out ios::ate All the date you write, is put at the end of the file. It does not call ios::out ios::trunc Deletes all previous content in the file. (empties the file) ios::nocreate If the file does not exist, opening it with the open() function gets impossible. ios::noreplace If the file exists, trying to open it with the open() function, returns an error. ios::binary Opens the file in binary mode.
  • 14. File Modes  Opening a file in ios::out mode also opens it in the ios::trunc mode by default. That is, if the file already exists, it is truncated  Both ios::app and ios::ate set the pointers to the end of file, but they differ in terms of the types of operations permitted on a file. The ios::app allows to add data from end of file, whereas ios::ate mode allows to add or modify the existing data anywhere in the file. In both the cases the file is created if it is non existent.  The mode ios::app can be used only with output files  The stream classes ifstream and ofstream open files in read and write modes by default.
  • 15. File pointers  Each file has two associated pointers known as the file pointers. One of them is called the input pointer or get pointer. The get pointer specifies a location from which the current reading operation is initiated Other is called the output pointer or put pointer. The put pointer specifies a location from where the current writing operation is initiated We can use these pointers to move through the files while reading or writing. The input pointer is used for reading the contents of a given file location and the output pointer is used for writing to a given file location. Functions for manipulation of file pointers seekg() Moves get pointer (input) to a specified location. seekp() Moves put pointer (output) to a specified location. tellg() Gives the current position of the get pointer. tellp() Gives the current position of the put pointer.
  • 16. File pointers infile.seekg(10); Moves the file pointer to the byte number 10. The bytes in a file are numbered beginning from zero. Thus, the pointer will be pointing to the 11th byte in the file. Specifying the offset : The seek functions seekg() and seekp() can also be used with two arguments as follows: seekg(offset, refposition); seekp(offset, refposition); The parameter offset represents the number of bytes the file pointer to be moved from the location specified by the parameter refposition. The refposition takes one of the following these constant defined in the ios class. ios::beg start of the file ios::cur current position of the pointer ios::end end of the file.
  • 17. File Open Mode #include <fstream> int main(void) { ofstream outFile("file1.txt", ios::out); outFile << "That's new!n"; outFile.close(); Return 0; } If you want to set more than one open mode, just use the OR operator- |. This way: ios::ate | ios::binary
  • 18. Dealing with Binary files Functions for binary file handlingFunctions for binary file handling get():get(): read a byte and point to the next byte to readread a byte and point to the next byte to read put():put(): write a byte and point to the next location forwrite a byte and point to the next location for writewrite read():read(): block readingblock reading write():write(): block writingblock writing flush():flush():Save data from the buffer to the output file.Save data from the buffer to the output file.
  • 19. Binary File I/O Examples //Example 1: Using get() and put() #include <iostream> #include <fstream> void main() { fstream File("test_file",ios::out | ios::in | ios::binary); char ch; ch='o'; File.put(ch); //put the content of ch to the file File.seekg(ios::beg); //go to the beginning of the file File.get(ch); //read one character cout << ch << endl; //display it File.close(); }
  • 20. File I/O Example: Writing #include <fstream>#include <fstream> using namespace std;using namespace std; int main(void)int main(void) {{ ofstream outFile(“fout.txt");ofstream outFile(“fout.txt"); outFile << "Hello World!";outFile << "Hello World!"; outFile.close();outFile.close(); return 0;return 0; }}
  • 21. File I/O Example: Reading #include <iostream>#include <iostream> #include <fstream>#include <fstream> int main(void)int main(void) {{ ifstream openFile(“data.txt"); //open a text file data.txtifstream openFile(“data.txt"); //open a text file data.txt char ch;char ch; while(!OpenFile.eof())while(!OpenFile.eof()) {{ OpenFile.get(ch);OpenFile.get(ch); cout << ch;cout << ch; }} OpenFile.close();OpenFile.close(); return 0;return 0; }}
  • 22. File I/O Example: Reading #include <iostream>#include <iostream> #include <fstream>#include <fstream> #include <string>#include <string> int main(void)int main(void) {{ ifstream openFile(“data.txt"); //open a text file data.txtifstream openFile(“data.txt"); //open a text file data.txt string line;string line; if(openFile.is_open()){ //if(openFile.is_open()){ // while(!openFile.eof()){while(!openFile.eof()){ getline(openFile,line);//read a line from data.txt and put it in a stringgetline(openFile,line);//read a line from data.txt and put it in a string cout << line;cout << line; }} else{else{ cout<<“File does not exist!”<<endl;cout<<“File does not exist!”<<endl; exit(1);}exit(1);} }} openFile.close();openFile.close(); return 0;return 0; }}
  • 23. To access file handling routines: #include <fstream.h> 2: To declare variables that can be used to access file: ifstream in_stream; ofstream out_stream; 3: To connect your program's variable (its internal name) to an external file (i.e., on the Unix file system): in_stream.open("infile.dat"); out_stream.open("outfile.dat"); 4: To see if the file opened successfully: if (in_stream.fail()) { cout << "Input file open failedn"; exit(1); // requires <stdlib.h>}
  • 24. To get data from a file (one option), must declare a variable to hold the data and then read it using the extraction operator: int num; in_stream >> num; [Compare: cin >> num;] 6: To put data into a file, use insertion operator: out_stream << num; [Compare: cout << num;] NOTE: Streams are sequential – data is read and written in order – generally can't back up. 7: When done with the file: in_stream.close(); out_stream.close();
  • 25. Reading /Writing from/to Binary Files  To write n bytes:  write (const unsigned char* buffer, int n);  To read n bytes (to a pre-allocated buffer):  read (unsighed char* buffer, int num) #include <fstream.h> main() { int array[] = {10,23,3,7,9,11,253}; ofstream OutBinaryFile("my_b_file.txt“, ios::out | ios::binary); OutBinaryFile.write((char*) array, sizeof(array)); OutBinaryFile.close(); }
  • 26. C++ has some low-level facilities for character I/O.C++ has some low-level facilities for character I/O. char next1, next2, next3;char next1, next2, next3; cin.get(next1);cin.get(next1); Gets the next character from the keyboard. Does not skip overGets the next character from the keyboard. Does not skip over blanks or newline (n). Can check for newline (next == 'n')blanks or newline (n). Can check for newline (next == 'n') Example:Example:  cin.get(next1);cin.get(next1);  cin.get(next2);cin.get(next2);  cin.get(next3);cin.get(next3); Predefined character functions must #include <ctype.h> and can be used to  convert between upper and lower case  test whether in upper or lower case  test whether alphabetic character or digit  test for space
  • 27. Reading /Writing from/to Textual Files #include <fstream.h> main() { // Writing to file ofstream OutFile("my_file.txt"); OutFile<<"Hello "<<5<<endl; OutFile.close(); int number; char dummy[15]; // Reading from file ifstream InFile("my_file.txt"); InFile>>dummy>>number; InFile.seekg(0); InFile.getline(dummy,sizeof(dummy)); InFile.close(); } To write: put() – writing single character << operator – writing an object To read: get() – reading a single character of a buffer getline() – reading a single line >> operator – reading a object
  • 28. Binary file operations In connection with a binary file, the file mode must contain the ios::binary mode along with other mode(s) To read & write a or on to a binary file, as the case may be blocks of data are accessed through the use of C++ read() and write() respectively.
  • 29. Handling binary data #include <fstream> using namespace std; int main(){ ifstream in(“binfile.dat”); ofstream out(“out.dat”); if(!in || !out) { // return} unsigned int buf[1024]; while(!in){ in.read(buf, sizeof(unsigned int)*1024); out.write(buf, sizeof(unsigned int)*1024); }