SlideShare a Scribd company logo
FILE HANDLING IN C++
SYLLABUS OUTLINE Data File Handling:  Need for a data file,  Types of data files – Text file and Binary file; Text File :  Basic file operations on text file:  Creating/Writing text into file,  Reading and manipulation of text from an already existing text File (accessing sequentially); Binary   File :  Creation of file, Writing data into file,  Searching for required data from file, Appending data to a file,  Insertion of data in sorted file,  Deletion of data from file,  Modification of data in a file; Implementation of above mentioned data file handling in C++; Components of C++ to be used with file handling:
Header file :  fstream.h; ifstream, ofstream, fstream classes;  Opening a text file in in, out, and app modes;  open(),  get(),  put(),  getline() and close() functions;  Detecting end-of-file (with or without using eof() function);  Opening a binary file using in, out, and app modes;  open(), read(), write() and close() functions; Detecting end-of-file (with or without using eof() function); tellg(), tellp(), seekg(), seekp() functions  SYLLABUS OUTLINE (Contd.)
All programs we looked earlier:  Introduction  input data from the keyboard . output data to the screen. Difficult to handle large amount of input  data. Output would also be lost as soon as we exit from the program. How do we store data permanently?. We can use secondary storage device.   Data is packaged up on the storage device as data structures called  files .
Files (Streams) Files are used to store data in a relatively permanent form, on floppy disk, hard disk, tape or other form of secondary storage. Files can hold huge amounts of data if need be. Ordinary variables (even records and arrays) are kept in main memory which is temporary and rather limited in size.  Lets put it in points…………..
Why use files? Convenient way to deal with large quantities of data.  Store data permanently (until file is deleted).  Avoid having to type data into program multiple times.  Share data between programs.
The following is a  comparison  of  the two types of storage………..
Main memory   Made up of RAM chips.  Used to hold a program when it is running, including the values of its variables (whether integer, char, an array, etc.)  Secondary memory   Usually a disk drive (or magnetic tape).  Used to hold files (where a file can contain data, a program, text, etc.)  Can hold rather large amounts of data.
Main memory   Can only hold relatively  small  amounts of data.  Is  temporary  (as soon as the program is done or the power goes out all of these values are gone).  Gives  fast   access  to the data (all electronic ).  Secondary memory   Can hold rather  large  amounts of data.  Is fairly  permanent . (A file remains even if the power goes out. It will last until you erase it, as long as the disk isn't damaged, at least.)  Access to the data is considerably  slower  (due to moving parts).
I/O in C++ I/O in C++ uses  streams A Stream is a general name given to  flow of data.
Flow of Data…. PROGRAM DEVICES OR FILES Input Stream >> Output Stream << Data Data istream class ostream class (Insertion operator)‏ (Extraction  operator)‏
More About Files….. Now we need to know: how to &quot; connect &quot;  file  to  program how to tell the program to  read  data how to tell the program to  write  data error checking and handling  eof
I/O in C++ Different streams are used to represent different kinds of  data flow. Each stream is associated with a particular  class , which contains  member functions  and  definitions  for dealing with that particular kind of data flow.
The following classes in C++ have access to file input and output functions: ifstream ofstream fstream File Related Classes
The Stream Class Hierarchy ios istream get()‏ getline()‏ read()‏ >> ostream put()‏ write()‏ << fstreambase iostream Ifstream Open()‏ Tellg()‏ Seekg()‏ Ofstream Open()‏ Tellp()‏ Seekp()‏ fstream NOTE : UPWARD ARROWS INDICATE THE BASE CLASS
OPENING A FILE 1. By using the  CONSTRUCTOR of the    stream class. ifstream transaction(“sales.dly”); ofstream result(“result.02”); 2. By using the open() function of the stream class ifstream transaction; transaction.open(“sales.dly”); (Associating a stream with a file)‏
File Mode Parameters PARAMETER MEANING ios::app Append to end-of file ios::ate goto end of file on opening ios::binary binary file ios::in Open existing file for reading ios::nocreate open fails if file doesn’t exist ios::noreplace open fails if file already exists ios::out creates new file for writing on ios::trunc Deletes contents if it exists The mode can combine two or more modes using bit wise or ( | )
Checking For Successful File Opening ifstream transaction(“sales.dly”); if (transcation == NULL)‏ { cout<<“unable to open sales.dly”; cin.get(); //  waits for the operator to press any key exit(1); }
Closing of File Stream_name.close(); e.g., transaction.close(); fl.close(); Note :  There is no need to give the physical file name at the time of closing a file.
Types of Files The two basic types of files are Text files &  Binary files
Text Files A text file consists of  readable  characters separated into lines by newline characters.  (On most PCs, the newline character is actually represented by the two-character sequence of carriage return (ASCII 13), line feed (ASCII 10).  (\n)
A  binary file  stores data to disk in the same form in which it is represented in main memory. If you ever try to edit a binary file containing numbers you will see that the numbers appear as  nonsense characters.  Binary Files
Not having to translate numbers into a readable form makes binary files somewhat more  efficient . Binary files also do not normally use anything to separate the data into lines.  Such a file is  just a stream of data  with nothing in particular to separate components.  Binary Files
When using a  binary  file we write whole record data to the file at once.  but the numbers in the binary file will  not  be  readable  in this way.  When using a  text  file, we write out separately each of the pieces of data about a given record. The text file will be  readable  by an editor Text Files Binary Files
for the  text file  we will use the usual  output operator(<<)  and will output each of the pieces of the record separately.  with the  text file  we will read each of the pieces of record from the file separately, using the usual  input operator(>>) For the  binary file  we will use  write  to write to the file,  With the  binary file  we will use the  read  function to read a whole record,  The programs to create the data files will differ in how they open the file and in how they write to the file.
: Sequential access . With this type of file access one must read the data in order, much like with a tape, whether the data is really stored on tape or not.   Random access  (or  direct access ). This type of file access lets you jump to any location in the file, then to any other, etc., all in a reasonable amount of time.  Types of File Access
FILE POINTERS
FILE POINTERS Each file object has two integer values associated with it : get pointer put pointer These values specify the byte number in the file where reading or writing will take place.
File pointers….. By default  reading pointer  is set at  the  beginning . By default  writing pointer  is set at the  end  (when you open file in ios::app mode)‏ There are times when  you must take control of the file pointers  yourself so that you can read from and write to an arbitrary location in the file.
Functions associated with file pointers : The  seekg()  and  tellg()  functions allow you to set and examine the  get pointer . The  seekp()  and  tellp()  functions allow you to set and examine the  put pointer .
seekg() function :  (with one argument) With one argument : fl.seekg(k); fl.seekp(k); where k is absolute position from the beginning. The start of the file is byte 0  It will result in moving the pointer as shown- Begin File End k bytes ^ File pointer
‘ seek’ functions : ( With two arguments ) Number of bytes  file  pointer to be moved Location   from where File  pointer is to be moved fl.seekg(offset, refposition); fl.seekp(offset, refposition); Refposition  takes one of the following forms : ios::beg Start of the file ios::cur current position of the pointer ios::end  End of the file
File Pointer offset calls fl.seekg(0,ios::beg); Go to start fl.seekg(0,ios::cur); Stay at the current position fl.seekg(0,ios::end); Go to the end of file fl.seekg(m,ios::beg); Move to (m+1)th byte in the file
File Pointer offset calls fl.seekg(m,ios::cur);   Go forward by m bytes  from current pos fl.seekg(-m,ios::beg);  Go backward by m bytes  from current pos fl.seekg(-m,ios::cur); Go backward by m bytes  from the end
seekg() function : ( With two arguments ) : Go backward by m bytes from the end m bytes fl.seekg(m,ios::cur); Go forward by m bytes from current pos fl.seekg(m,ios::beg); Move to (m+1)th byte in the file m bytes Begin End End Begin m bytes Begin End ^ Offset from Begin ^ Offset from current position ^ Offset from end fl.seekg(-m,ios::cur);
EXAMPLES Creation of  a  text  file
#include <fstream.h> #include <conio.h> #include <stdio.h> void main()‏ { clrscr(); char c,d,ans; char str[80]; ofstream outfl(&quot;try.txt&quot;); do {  cout<<&quot;please give the string : &quot;; gets(str); outfl<<str; cout <<&quot;do you want to write  more...<y/n> : &quot;; ans=getch(); }  while(ans=='y'); outfl<<'\0'; outfl.close(); clrscr();  ifstream infl; getch(); cout <<&quot;reading from created file \n&quot;; infl.open(&quot;try.txt&quot;); out.open(&quot;cod.dat&quot;); //********************************** c=infl.get(); do {  d=c+1; cout<<c<<d<<'\n'; out.put(d); c= infl.get(); }  while (c!='\0'); out<<'\0'; infl.close(); outfl.close(); getch(); //********************************* } Program to generate coded file…… (Text File)
The End
Ad

More Related Content

What's hot (20)

Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++
Shyam Gupta
 
Constructors and Destructor in C++
Constructors and Destructor in C++Constructors and Destructor in C++
Constructors and Destructor in C++
International Institute of Information Technology (I²IT)
 
File handling
File handlingFile handling
File handling
Nilesh Dalvi
 
File in c
File in cFile in c
File in c
Prabhu Govind
 
File handling in c
File handling in cFile handling in c
File handling in c
aakanksha s
 
Files and streams
Files and streamsFiles and streams
Files and streams
Pranali Chaudhari
 
Function C programming
Function C programmingFunction C programming
Function C programming
Appili Vamsi Krishna
 
File Pointers
File PointersFile Pointers
File Pointers
Kulachi Hansraj Model School Ashok Vihar
 
C functions
C functionsC functions
C functions
University of Potsdam
 
Types of Constructor in C++
Types of Constructor in C++Types of Constructor in C++
Types of Constructor in C++
Bhavik Vashi
 
File handling in c
File handling in cFile handling in c
File handling in c
David Livingston J
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
rprajat007
 
Managing input and output operation in c
Managing input and output operation in cManaging input and output operation in c
Managing input and output operation in c
yazad dumasia
 
File handling-c
File handling-cFile handling-c
File handling-c
CGC Technical campus,Mohali
 
Files in Python.pptx
Files in Python.pptxFiles in Python.pptx
Files in Python.pptx
Koteswari Kasireddy
 
virtual function
virtual functionvirtual function
virtual function
VENNILAV6
 
Input and output in C++
Input and output in C++Input and output in C++
Input and output in C++
Nilesh Dalvi
 
Function in C program
Function in C programFunction in C program
Function in C program
Nurul Zakiah Zamri Tan
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
Vishal Patil
 
Call by value
Call by valueCall by value
Call by value
Dharani G
 

Similar to File Handling In C++ (20)

Filepointers1 1215104829397318-9
Filepointers1 1215104829397318-9Filepointers1 1215104829397318-9
Filepointers1 1215104829397318-9
AbdulghafarStanikzai
 
Filehandlinging cp2
Filehandlinging cp2Filehandlinging cp2
Filehandlinging cp2
Tanmay Baranwal
 
File Handling In C++(OOPs))
File Handling In C++(OOPs))File Handling In C++(OOPs))
File Handling In C++(OOPs))
Papu Kumar
 
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
AzanMehdi
 
file_handling_in_c.pptbbbbbbbbbbbbbbbbbbbbb
file_handling_in_c.pptbbbbbbbbbbbbbbbbbbbbbfile_handling_in_c.pptbbbbbbbbbbbbbbbbbbbbb
file_handling_in_c.pptbbbbbbbbbbbbbbbbbbbbb
SanskritiGupta39
 
File handling in_c
File handling in_cFile handling in_c
File handling in_c
sanya6900
 
Data file handling
Data file handlingData file handling
Data file handling
Prof. Dr. K. Adisesha
 
File Handling
File HandlingFile Handling
File Handling
TusharBatra27
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
pinkpreet_kaur
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
pinkpreet_kaur
 
7 Data File Handling
7 Data File Handling7 Data File Handling
7 Data File Handling
Praveen M Jigajinni
 
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
 
File management in C++
File management in C++File management in C++
File management in C++
apoorvaverma33
 
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
 
File Management and manipulation in C++ Programming
File Management and manipulation in C++ ProgrammingFile Management and manipulation in C++ Programming
File Management and manipulation in C++ Programming
ChereLemma2
 
Filesin c++
Filesin c++Filesin c++
Filesin c++
HalaiHansaika
 
Data file handling in c++
Data file handling in c++Data file handling in c++
Data file handling in c++
Vineeta Garg
 
working with files
working with filesworking with files
working with files
SangeethaSasi1
 
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUSFILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
Venugopalavarma Raja
 
File Handling
File HandlingFile Handling
File Handling
AlgeronTongdoTopi
 
File Handling In C++(OOPs))
File Handling In C++(OOPs))File Handling In C++(OOPs))
File Handling In C++(OOPs))
Papu Kumar
 
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
AzanMehdi
 
file_handling_in_c.pptbbbbbbbbbbbbbbbbbbbbb
file_handling_in_c.pptbbbbbbbbbbbbbbbbbbbbbfile_handling_in_c.pptbbbbbbbbbbbbbbbbbbbbb
file_handling_in_c.pptbbbbbbbbbbbbbbbbbbbbb
SanskritiGupta39
 
File handling in_c
File handling in_cFile handling in_c
File handling in_c
sanya6900
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
pinkpreet_kaur
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
pinkpreet_kaur
 
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
 
File management in C++
File management in C++File management in C++
File management in C++
apoorvaverma33
 
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
 
File Management and manipulation in C++ Programming
File Management and manipulation in C++ ProgrammingFile Management and manipulation in C++ Programming
File Management and manipulation in C++ Programming
ChereLemma2
 
Data file handling in c++
Data file handling in c++Data file handling in c++
Data file handling in c++
Vineeta Garg
 
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUSFILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
Venugopalavarma Raja
 
Ad

More from Kulachi Hansraj Model School Ashok Vihar (20)

Edge 2010
Edge 2010Edge 2010
Edge 2010
Kulachi Hansraj Model School Ashok Vihar
 
Story 1
Story 1Story 1
Story 1
Kulachi Hansraj Model School Ashok Vihar
 
Butterfly
ButterflyButterfly
Butterfly
Kulachi Hansraj Model School Ashok Vihar
 
A message of stephen covey
A message of stephen coveyA message of stephen covey
A message of stephen covey
Kulachi Hansraj Model School Ashok Vihar
 
Stack Applications
Stack ApplicationsStack Applications
Stack Applications
Kulachi Hansraj Model School Ashok Vihar
 
Conversion of Infix To Postfix Expressions
Conversion of Infix To Postfix Expressions Conversion of Infix To Postfix Expressions
Conversion of Infix To Postfix Expressions
Kulachi Hansraj Model School Ashok Vihar
 
Loops
LoopsLoops
Loops
Kulachi Hansraj Model School Ashok Vihar
 
robotics workshop Aug.09
robotics workshop Aug.09robotics workshop Aug.09
robotics workshop Aug.09
Kulachi Hansraj Model School Ashok Vihar
 
Computer System Organization
Computer System OrganizationComputer System Organization
Computer System Organization
Kulachi Hansraj Model School Ashok Vihar
 
Tut Constructor
Tut ConstructorTut Constructor
Tut Constructor
Kulachi Hansraj Model School Ashok Vihar
 
Think It
Think ItThink It
Think It
Kulachi Hansraj Model School Ashok Vihar
 
Edge2008
Edge2008Edge2008
Edge2008
Kulachi Hansraj Model School Ashok Vihar
 
Programming Methodology
Programming MethodologyProgramming Methodology
Programming Methodology
Kulachi Hansraj Model School Ashok Vihar
 
Arrays
ArraysArrays
Arrays
Kulachi Hansraj Model School Ashok Vihar
 
Robot Timeline
Robot TimelineRobot Timeline
Robot Timeline
Kulachi Hansraj Model School Ashok Vihar
 
Prefix Postfix
Prefix PostfixPrefix Postfix
Prefix Postfix
Kulachi Hansraj Model School Ashok Vihar
 
Looping
LoopingLooping
Looping
Kulachi Hansraj Model School Ashok Vihar
 
Computer Fundamentals
Computer FundamentalsComputer Fundamentals
Computer Fundamentals
Kulachi Hansraj Model School Ashok Vihar
 
Number System
Number SystemNumber System
Number System
Kulachi Hansraj Model School Ashok Vihar
 
Computer Parts
Computer PartsComputer Parts
Computer Parts
Kulachi Hansraj Model School Ashok Vihar
 
Ad

Recently uploaded (20)

Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 

File Handling In C++

  • 2. SYLLABUS OUTLINE Data File Handling: Need for a data file, Types of data files – Text file and Binary file; Text File : Basic file operations on text file: Creating/Writing text into file, Reading and manipulation of text from an already existing text File (accessing sequentially); Binary File : Creation of file, Writing data into file, Searching for required data from file, Appending data to a file, Insertion of data in sorted file, Deletion of data from file, Modification of data in a file; Implementation of above mentioned data file handling in C++; Components of C++ to be used with file handling:
  • 3. Header file : fstream.h; ifstream, ofstream, fstream classes; Opening a text file in in, out, and app modes; open(), get(), put(), getline() and close() functions; Detecting end-of-file (with or without using eof() function); Opening a binary file using in, out, and app modes; open(), read(), write() and close() functions; Detecting end-of-file (with or without using eof() function); tellg(), tellp(), seekg(), seekp() functions SYLLABUS OUTLINE (Contd.)
  • 4. All programs we looked earlier: Introduction input data from the keyboard . output data to the screen. Difficult to handle large amount of input data. Output would also be lost as soon as we exit from the program. How do we store data permanently?. We can use secondary storage device. Data is packaged up on the storage device as data structures called files .
  • 5. Files (Streams) Files are used to store data in a relatively permanent form, on floppy disk, hard disk, tape or other form of secondary storage. Files can hold huge amounts of data if need be. Ordinary variables (even records and arrays) are kept in main memory which is temporary and rather limited in size. Lets put it in points…………..
  • 6. Why use files? Convenient way to deal with large quantities of data. Store data permanently (until file is deleted). Avoid having to type data into program multiple times. Share data between programs.
  • 7. The following is a comparison of the two types of storage………..
  • 8. Main memory Made up of RAM chips. Used to hold a program when it is running, including the values of its variables (whether integer, char, an array, etc.) Secondary memory Usually a disk drive (or magnetic tape). Used to hold files (where a file can contain data, a program, text, etc.) Can hold rather large amounts of data.
  • 9. Main memory Can only hold relatively small amounts of data. Is temporary (as soon as the program is done or the power goes out all of these values are gone). Gives fast access to the data (all electronic ). Secondary memory Can hold rather large amounts of data. Is fairly permanent . (A file remains even if the power goes out. It will last until you erase it, as long as the disk isn't damaged, at least.) Access to the data is considerably slower (due to moving parts).
  • 10. I/O in C++ I/O in C++ uses streams A Stream is a general name given to flow of data.
  • 11. Flow of Data…. PROGRAM DEVICES OR FILES Input Stream >> Output Stream << Data Data istream class ostream class (Insertion operator)‏ (Extraction operator)‏
  • 12. More About Files….. Now we need to know: how to &quot; connect &quot; file to program how to tell the program to read data how to tell the program to write data error checking and handling eof
  • 13. I/O in C++ Different streams are used to represent different kinds of data flow. Each stream is associated with a particular class , which contains member functions and definitions for dealing with that particular kind of data flow.
  • 14. The following classes in C++ have access to file input and output functions: ifstream ofstream fstream File Related Classes
  • 15. The Stream Class Hierarchy ios istream get()‏ getline()‏ read()‏ >> ostream put()‏ write()‏ << fstreambase iostream Ifstream Open()‏ Tellg()‏ Seekg()‏ Ofstream Open()‏ Tellp()‏ Seekp()‏ fstream NOTE : UPWARD ARROWS INDICATE THE BASE CLASS
  • 16. OPENING A FILE 1. By using the CONSTRUCTOR of the stream class. ifstream transaction(“sales.dly”); ofstream result(“result.02”); 2. By using the open() function of the stream class ifstream transaction; transaction.open(“sales.dly”); (Associating a stream with a file)‏
  • 17. File Mode Parameters PARAMETER MEANING ios::app Append to end-of file ios::ate goto end of file on opening ios::binary binary file ios::in Open existing file for reading ios::nocreate open fails if file doesn’t exist ios::noreplace open fails if file already exists ios::out creates new file for writing on ios::trunc Deletes contents if it exists The mode can combine two or more modes using bit wise or ( | )
  • 18. Checking For Successful File Opening ifstream transaction(“sales.dly”); if (transcation == NULL)‏ { cout<<“unable to open sales.dly”; cin.get(); // waits for the operator to press any key exit(1); }
  • 19. Closing of File Stream_name.close(); e.g., transaction.close(); fl.close(); Note : There is no need to give the physical file name at the time of closing a file.
  • 20. Types of Files The two basic types of files are Text files & Binary files
  • 21. Text Files A text file consists of readable characters separated into lines by newline characters. (On most PCs, the newline character is actually represented by the two-character sequence of carriage return (ASCII 13), line feed (ASCII 10). (\n)
  • 22. A binary file stores data to disk in the same form in which it is represented in main memory. If you ever try to edit a binary file containing numbers you will see that the numbers appear as nonsense characters. Binary Files
  • 23. Not having to translate numbers into a readable form makes binary files somewhat more efficient . Binary files also do not normally use anything to separate the data into lines. Such a file is just a stream of data with nothing in particular to separate components. Binary Files
  • 24. When using a binary file we write whole record data to the file at once. but the numbers in the binary file will not be readable in this way. When using a text file, we write out separately each of the pieces of data about a given record. The text file will be readable by an editor Text Files Binary Files
  • 25. for the text file we will use the usual output operator(<<) and will output each of the pieces of the record separately. with the text file we will read each of the pieces of record from the file separately, using the usual input operator(>>) For the binary file we will use write to write to the file, With the binary file we will use the read function to read a whole record, The programs to create the data files will differ in how they open the file and in how they write to the file.
  • 26. : Sequential access . With this type of file access one must read the data in order, much like with a tape, whether the data is really stored on tape or not. Random access (or direct access ). This type of file access lets you jump to any location in the file, then to any other, etc., all in a reasonable amount of time. Types of File Access
  • 28. FILE POINTERS Each file object has two integer values associated with it : get pointer put pointer These values specify the byte number in the file where reading or writing will take place.
  • 29. File pointers….. By default reading pointer is set at the beginning . By default writing pointer is set at the end (when you open file in ios::app mode)‏ There are times when you must take control of the file pointers yourself so that you can read from and write to an arbitrary location in the file.
  • 30. Functions associated with file pointers : The seekg() and tellg() functions allow you to set and examine the get pointer . The seekp() and tellp() functions allow you to set and examine the put pointer .
  • 31. seekg() function : (with one argument) With one argument : fl.seekg(k); fl.seekp(k); where k is absolute position from the beginning. The start of the file is byte 0 It will result in moving the pointer as shown- Begin File End k bytes ^ File pointer
  • 32. ‘ seek’ functions : ( With two arguments ) Number of bytes file pointer to be moved Location from where File pointer is to be moved fl.seekg(offset, refposition); fl.seekp(offset, refposition); Refposition takes one of the following forms : ios::beg Start of the file ios::cur current position of the pointer ios::end End of the file
  • 33. File Pointer offset calls fl.seekg(0,ios::beg); Go to start fl.seekg(0,ios::cur); Stay at the current position fl.seekg(0,ios::end); Go to the end of file fl.seekg(m,ios::beg); Move to (m+1)th byte in the file
  • 34. File Pointer offset calls fl.seekg(m,ios::cur); Go forward by m bytes from current pos fl.seekg(-m,ios::beg); Go backward by m bytes from current pos fl.seekg(-m,ios::cur); Go backward by m bytes from the end
  • 35. seekg() function : ( With two arguments ) : Go backward by m bytes from the end m bytes fl.seekg(m,ios::cur); Go forward by m bytes from current pos fl.seekg(m,ios::beg); Move to (m+1)th byte in the file m bytes Begin End End Begin m bytes Begin End ^ Offset from Begin ^ Offset from current position ^ Offset from end fl.seekg(-m,ios::cur);
  • 36. EXAMPLES Creation of a text file
  • 37. #include <fstream.h> #include <conio.h> #include <stdio.h> void main()‏ { clrscr(); char c,d,ans; char str[80]; ofstream outfl(&quot;try.txt&quot;); do { cout<<&quot;please give the string : &quot;; gets(str); outfl<<str; cout <<&quot;do you want to write more...<y/n> : &quot;; ans=getch(); } while(ans=='y'); outfl<<'\0'; outfl.close(); clrscr(); ifstream infl; getch(); cout <<&quot;reading from created file \n&quot;; infl.open(&quot;try.txt&quot;); out.open(&quot;cod.dat&quot;); //********************************** c=infl.get(); do { d=c+1; cout<<c<<d<<'\n'; out.put(d); c= infl.get(); } while (c!='\0'); out<<'\0'; infl.close(); outfl.close(); getch(); //********************************* } Program to generate coded file…… (Text File)