SlideShare a Scribd company logo
Basics of File
 Handling
  Name-Pinkpreet Kaur
      Section-N1
    Roll no.-115329
Contents of presentation
 Using input/output files
 General files I/O steps
 Using input/output files
 Streams
 Predifined console streams
 File modes
 File pointers
 Binary file operations
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 file
   is stored on a secondary storage device
    (e.g., disk);
   is permanent;
   can be used to provide input data to a
    program or receive output data from a
    program, or both;
   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
basics of file handling
Using Input/Output Files
         stream - a sequence of characters
            interactive (iostream)
               cin - input stream associated with keyboard.
               cout - output stream associated with display.
            file (fstream)
               ifstream - defines new input stream (normally associated
                 with a file).
               ofstream - defines new output stream (normally 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
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 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 handling
 get(): read a byte and point to the next byte to
 read
 put(): write a byte and point to the next location for
 write
 read(): block reading
 write(): block writing

 flush():Save data from the buffer to the output file.
Reading /Writing from/to Textual Files

                                              #include <fstream.h>
To write:                                        main()
    put() – writing single character             {
    << operator – writing an object                     // Writing to file
                                                        ofstream OutFile("my_file.txt");
To read:
                                                        OutFile<<"Hello "<<5<<endl;
    get() – reading a single character of a             OutFile.close();
    buffer
    getline() – reading a single line                  int number;
    >> operator – reading a object                     char dummy[15];


                                                // Reading from file
                                                       ifstream InFile("my_file.txt");
                                                       InFile>>dummy>>number;


                                                InFile.seekg(0);

                                                InFile.getline(dummy,sizeof(dummy));
                                                       InFile.close();
                                                }
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);
}
THANKS

More Related Content

What's hot (19)

PPT
File handling
Nilesh Dalvi
 
PPT
Cpp file-handling
JiaahRajpout123
 
PPSX
Files in c++
Selvin Josy Bai Somu
 
PPT
Filehandlinging cp2
Tanmay Baranwal
 
PPT
17 files and streams
Docent Education
 
PPTX
Data file handling in c++
Vineeta Garg
 
DOCX
File handling in c++
Daniel Nyagechi
 
PDF
08. handling file streams
Haresh Jaiswal
 
PPT
Files in c++ ppt
Kumar
 
PDF
Filehadnling
Khushal Mehta
 
PPTX
File handling in c++
ProfSonaliGholveDoif
 
PPT
working file handling in cpp overview
gourav kottawar
 
PPTX
Files in c++
NivethaJeyaraman
 
PDF
file handling c++
Guddu Spy
 
PPTX
UNIT 10. Files and file handling in C
Ashim Lamichhane
 
PPTX
Filesin c++
HalaiHansaika
 
File handling
Nilesh Dalvi
 
Cpp file-handling
JiaahRajpout123
 
Files in c++
Selvin Josy Bai Somu
 
Filehandlinging cp2
Tanmay Baranwal
 
17 files and streams
Docent Education
 
Data file handling in c++
Vineeta Garg
 
File handling in c++
Daniel Nyagechi
 
08. handling file streams
Haresh Jaiswal
 
Files in c++ ppt
Kumar
 
Filehadnling
Khushal Mehta
 
File handling in c++
ProfSonaliGholveDoif
 
working file handling in cpp overview
gourav kottawar
 
Files in c++
NivethaJeyaraman
 
file handling c++
Guddu Spy
 
UNIT 10. Files and file handling in C
Ashim Lamichhane
 
Filesin c++
HalaiHansaika
 

Viewers also liked (8)

PPT
Socket System Calls
Avinash Varma Kalidindi
 
PPT
Java Input Output and File Handling
Sunil OS
 
PPSX
Congestion control in TCP
selvakumar_b1985
 
PPTX
Routing Protocols and Concepts - Chapter 1
CAVC
 
PPT
14 file handling
APU
 
PPT
TCP congestion control
Shubham Jain
 
PDF
Java Course 8: I/O, Files and Streams
Anton Keks
 
PPT
Socket programming
chandramouligunnemeda
 
Socket System Calls
Avinash Varma Kalidindi
 
Java Input Output and File Handling
Sunil OS
 
Congestion control in TCP
selvakumar_b1985
 
Routing Protocols and Concepts - Chapter 1
CAVC
 
14 file handling
APU
 
TCP congestion control
Shubham Jain
 
Java Course 8: I/O, Files and Streams
Anton Keks
 
Socket programming
chandramouligunnemeda
 
Ad

Similar to basics of file handling (20)

PPT
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
AzanMehdi
 
PPT
file_handling_in_c.ppt......................................
nadoj47203
 
PPT
file_handling_in_c.pptbbbbbbbbbbbbbbbbbbbbb
SanskritiGupta39
 
PDF
Basics of files and its functions with example
Sunil Patel
 
PDF
Files and streams
Pranali Chaudhari
 
DOCX
Filehandling
Muhammad Fahad
 
PDF
Filepointers1 1215104829397318-9
AbdulghafarStanikzai
 
PPTX
File Handling
TusharBatra27
 
PPTX
File management in C++
apoorvaverma33
 
PPTX
Chapter4.pptx
WondimuBantihun1
 
PPTX
Programming Fundamentals lecture-22.pptx
singyali199
 
PPTX
File Handling in CPP Programming Language.pptx
SajjadAbdullah4
 
PDF
Data file handling
Prof. Dr. K. Adisesha
 
PPTX
File handling
Amber Wajid
 
PDF
Filesinc 130512002619-phpapp01
Rex Joe
 
PDF
Chapter28 data-file-handling
Deepak Singh
 
PDF
File Handling.pdffile handling ppt final
e13225064
 
PPT
7 Data File Handling
Praveen M Jigajinni
 
PDF
File handling
Swarup Kumar Boro
 
PPTX
Working with files in c++. file handling
tfluid16
 
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
AzanMehdi
 
file_handling_in_c.ppt......................................
nadoj47203
 
file_handling_in_c.pptbbbbbbbbbbbbbbbbbbbbb
SanskritiGupta39
 
Basics of files and its functions with example
Sunil Patel
 
Files and streams
Pranali Chaudhari
 
Filehandling
Muhammad Fahad
 
Filepointers1 1215104829397318-9
AbdulghafarStanikzai
 
File Handling
TusharBatra27
 
File management in C++
apoorvaverma33
 
Chapter4.pptx
WondimuBantihun1
 
Programming Fundamentals lecture-22.pptx
singyali199
 
File Handling in CPP Programming Language.pptx
SajjadAbdullah4
 
Data file handling
Prof. Dr. K. Adisesha
 
File handling
Amber Wajid
 
Filesinc 130512002619-phpapp01
Rex Joe
 
Chapter28 data-file-handling
Deepak Singh
 
File Handling.pdffile handling ppt final
e13225064
 
7 Data File Handling
Praveen M Jigajinni
 
File handling
Swarup Kumar Boro
 
Working with files in c++. file handling
tfluid16
 
Ad

Recently uploaded (20)

PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
Predicting the unpredictable: re-engineering recommendation algorithms for fr...
Speck&Tech
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PDF
Wojciech Ciemski for Top Cyber News MAGAZINE. June 2025
Dr. Ludmila Morozova-Buss
 
PDF
Persuasive AI: risks and opportunities in the age of digital debate
Speck&Tech
 
PDF
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
TrustArc Webinar - Data Privacy Trends 2025: Mid-Year Insights & Program Stra...
TrustArc
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PDF
Building Resilience with Digital Twins : Lessons from Korea
SANGHEE SHIN
 
PDF
SFWelly Summer 25 Release Highlights July 2025
Anna Loughnan Colquhoun
 
PDF
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PDF
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PDF
Why Orbit Edge Tech is a Top Next JS Development Company in 2025
mahendraalaska08
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
Predicting the unpredictable: re-engineering recommendation algorithms for fr...
Speck&Tech
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
Wojciech Ciemski for Top Cyber News MAGAZINE. June 2025
Dr. Ludmila Morozova-Buss
 
Persuasive AI: risks and opportunities in the age of digital debate
Speck&Tech
 
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
TrustArc Webinar - Data Privacy Trends 2025: Mid-Year Insights & Program Stra...
TrustArc
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
Building Resilience with Digital Twins : Lessons from Korea
SANGHEE SHIN
 
SFWelly Summer 25 Release Highlights July 2025
Anna Loughnan Colquhoun
 
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
Why Orbit Edge Tech is a Top Next JS Development Company in 2025
mahendraalaska08
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 

basics of file handling

  • 1. Basics of File Handling Name-Pinkpreet Kaur Section-N1 Roll no.-115329
  • 2. Contents of presentation  Using input/output files  General files I/O steps  Using input/output files  Streams  Predifined console streams  File modes  File pointers  Binary file operations
  • 3. 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.
  • 4. Using Input/Output Files A computer file  is stored on a secondary storage device (e.g., disk);  is permanent;  can be used to provide input data to a program or receive output data from a program, or both;  must be opened before it is used.
  • 5. 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
  • 6. 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
  • 8. Using Input/Output Files  stream - a sequence of characters  interactive (iostream)  cin - input stream associated with keyboard.  cout - output stream associated with display.  file (fstream)  ifstream - defines new input stream (normally associated with a file).  ofstream - defines new output stream (normally 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
  • 9. 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.
  • 10. 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)
  • 11. 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
  • 12. 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.
  • 13. 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.
  • 14. 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.
  • 15. 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
  • 16. Dealing with Binary files  Functions for binary file handling get(): read a byte and point to the next byte to read put(): write a byte and point to the next location for write read(): block reading write(): block writing flush():Save data from the buffer to the output file.
  • 17. Reading /Writing from/to Textual Files #include <fstream.h> To write: main() put() – writing single character { << operator – writing an object // Writing to file ofstream OutFile("my_file.txt"); To read: OutFile<<"Hello "<<5<<endl; get() – reading a single character of a OutFile.close(); buffer getline() – reading a single line int number; >> operator – reading a object char dummy[15]; // Reading from file ifstream InFile("my_file.txt"); InFile>>dummy>>number; InFile.seekg(0); InFile.getline(dummy,sizeof(dummy)); InFile.close(); }
  • 18. 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.
  • 19. 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); }