SlideShare une entreprise Scribd logo
1  sur  35
10/7/2012
    FILE HANDALING
1




       G.vishnuprabhu
CONTENTS:




                                               10/7/2012
 File pointer and their manipulation
 Sequential input and output operations

 Adding content to a file




                                           2
10/7/2012
INTRODUCTION




               3
HOW TO OPEN A FILE IN C++ ?




                                              10/7/2012
   #include<fstream.h>

 ofstream streamname(“filename”, mode)
            or
 Ofstream streamname;

  streamname.open(“filename”, mode)




                                          4
   To create a file:

        #include<fstream.h>




                                                 10/7/2012
        main()
        {
               fstream file(“newdoc.txt”);
               file.close();
        }




                                             5
   To write into a file:

         #include<fstream.h>




                                                              10/7/2012
         main()
         {
                ofstream file(“newdoc.txt”);
                file<<“my first file handling program”;
                file.close();
         }




                                                          6
   To close a file:

     The file is closed implicitly when a destructor for




                                                               10/7/2012
    the corresponding object is called


         (Or)


         Obj.close()




                                                           7
10/7/2012
FILE POINTERS


                8
FILE POINTERS:




                                                          10/7/2012
   The c++ input and output system manages two int
    value associates with a file

   These are
        1)get pointer
        2)put pointer




                                                      9
OPENING IN A FILE IN DIFFERENT MODES




                                                                 10/7/2012
 Read      h    e     l        l   o   w    o     r     l   d
 only
               Input pointer


append     h    e     l        l   o   w o        r     l   d

                                           Output pointer


 writing


           Output pointer                                       10
10/7/2012
Get pointer                     Put pointer

   It specifies the location      It specifies the location
    in a file where the next        in a file where the next
    read operation will             write operation will
    occur                           occur




                                                                11
FUNCTIONS




             10/7/2012
 tellg()
 tellp()

 seekg()

 seekp()




            12
FILE POSITION POINTER




                                                              10/7/2012
   <istream> and <ostream> classes provide member
    functions for repositioning the file pointer (the byte
    number of the next byte in the file to be read or to
    be written.)

   These member functions are:
    seekg (seek get) for istream class
    seekp (seek put) for ostream class



                                                             13
EXAMPLES OF MOVING A FILE POINTER




                                                              10/7/2012
obj.seekg(0) –
                   repositions the file get pointer to the
                   beginning of the file
obj.seekg(0, ios:end) –
                    repositions the file get pointer to
                   the end of the file




                                                             14
obj.seekg(n, ios:beg) –
                   repositions the file
                   get pointer to the n-th byte of the




                                                            10/7/2012
                   file
obj.seekg(m, ios:end) –
                   repositions the file
                   get pointer to the m-th byte from the
                   end of file



The same operations can be performed with
<ostream> function member seekp.

                                                           15
MEMBER FUNCTIONS TELLG() AND TELLP().




                                                     10/7/2012
 Member   functions tellg and tellp are
  provided to return the current locations of
  the get and put pointers, respectively.
 long location = inClientFile.tellg();

 To move the pointer relative to the current
  location use ios:cur
 inClientFile.seekg(n, ios:cur) - moves the file
  get pointer n bytes forward.

                                                    16
10/7/2012
SEQUENTIAL INPUT AND OUTPUT OPERATIONS


                                         17
CREATING A SEQUENTIAL FILE




                                                          10/7/2012
// Create a sequential file
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
int main()
{
    // ofstream constructor opens file
    ofstream outClientFile( "clients.dat", ios::out );


    if ( !outClientFile ) { // overloaded ! operator
        cerr << "File could not be opened" << endl;
        exit( 1 );   // prototype in stdlib.h
    }                                                    18
SEQUENTIAL FILE
cout << "Enter the account, name, and balance.n"




                                                     10/7/2012
     << "Enter end-of-file to end input.n? ";
  int account;
 char name[ 30 ];
 float balance;

    while ( cin >> account >> name >> balance ) {
      outClientFile << account << ' ' << name
               << ' ' << balance << 'n';
      cout << "? ";
    }

    return 0; // ofstream destructor closes file
}


                                                    19
UPDATING A SEQUENTIAL FILE




                                                         10/7/2012
 Data that is formatted and written to a sequential
  file cannot be modified easily without the risk of
  destroying other data in the file.
 If we want to modify a record of data, the new data
  may be longer than the old one and it could
  overwrite parts of the record following it.




                                                        20
PROBLEMS WITH SEQUENTIAL FILES




                                                         10/7/2012
 Sequential files are inappropriate for so-called
  “instant access” applications in which a particular
  record of information must be located immediately.
 These applications include banking systems, point-
  of-sale systems, airline reservation systems, (or
  any data-base system.)




                                                        21
RANDOM ACCESS FILES




                                                            10/7/2012
   Instant access is possible with random access files.

   Individual records of a random access file can be
    accessed directly (and quickly) without searching
    many other records.




                                                           22
EXAMPLE OF A PROGRAM THAT CREATES A
RANDOM ACCESS FILE




                                              10/7/2012
// Definition of struct clientData used in
// Figs. 14.11, 14.12, 14.14 and 14.15.
#ifndef CLNTDATA_H
#define CLNTDATA_H
struct clientData {
   int accountNumber;
   char lastName[ 15 ];
   char firstName[ 10 ];
   float balance;
};
#endif
                                             23
CREATING A RANDOM ACCESS FILE




                                                      10/7/2012
// Creating a randomly accessed file sequentially
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
#include "clntdata.h"
int main()
{
    ofstream outCredit( "credit1.dat", ios::out);
if ( !outCredit ) {
      cerr << "File could not be opened." << endl;
      exit( 1 );
   }

                                                     24
CLIENTDATA BLANKCLIENT   = { 0, "", "", 0.0 };




                                                  10/7/2012
FOR ( INT I = 0; I < 100; I++ )
  OUTCREDIT.WRITE
       (REINTERPRET_CAST<CONST CHAR        *>(
&BLANKCLIENT ),
       SIZEOF( CLIENTDATA ) );
  RETURN 0;
}



                                                 25
<OSTREAM> MEMEBR FUNCTION WRITE




                                                              10/7/2012
   The <ostream> member function write outputs a
    fixed number of bytes beginning at a specific
    location in memory to the specific stream. When the
    stream is associated with a file, the data is written
    beginning at the location in the file specified by the
    “put” file pointer.




                                                             26
THE WRITE FUNCTION EXPECTS A FIRST
ARGUMENT OF TYPE CONST CHAR *,




                                      10/7/2012
HENCE WE USED THE
REINTERPRET_CAST <CONST CHAR *>
TO CONVERT THE ADDRESS OF THE
BLANKCLIENT TO A CONST CHAR *.
THE SECOND ARGUMENT OF WRITE IS
AN INTEGER OF TYPE SIZE_T
SPECIFYING THE NUMBER OF BYTES TO
WRITTEN. THUS THE SIZEOF(
                                     27
CLIENTDATA ).
WRITING DATA RANDOMLY TO A RANDOM FILE




                                                     10/7/2012
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
#include "clntdata.h"
int main()
{
  ofstream outCredit( "credit.dat", ios::ate );

  if ( !outCredit ) {
     cerr << "File could not be opened." << endl;
     exit( 1 );
  }

                                                    28
10/7/2012
COUT<< "ENTER ACCOUNT NUMBER "
   << "(1 TO 100, 0 TO END INPUT)N? ";

CLIENTDATA CLIENT;
CIN >> CLIENT.ACCOUNTNUMBER;

WHILE ( CLIENT.ACCOUNTNUMBER > 0 &&
    CLIENT.ACCOUNTNUMBER <= 100 ) {
 COUT << "ENTER LASTNAME, FIRSTNAME, BALANCEN?   ";
 CIN >> CLIENT.LASTNAME >> CLIENT.FIRSTNAME
    >> CLIENT.BALANCE;


                                                       29
OUTCREDIT.SEEKP( ( CLIENT.ACCOUNTNUMBER       -1)*




                                                         10/7/2012
             SIZEOF( CLIENTDATA ) );
   OUTCREDIT.WRITE(
         REINTERPRET_CAST<CONST CHAR   *>( &CLIENT ),
         SIZEOF( CLIENTDATA ) );


        COUT << "ENTER ACCOUNT NUMBERN? ";
        CIN >> CLIENT.ACCOUNTNUMBER;
    }

    RETURN     0;
}
                                                        30
READING DATA FROM A RANDOM FILE




                                                     10/7/2012
#include <iostream.h>
#include <iomanip.h>
#include <fstream.h>
#include <stdlib.h>
#include "clntdata.h"
void outputLine( ostream&, const clientData & );
int main()
{
  ifstream inCredit( "credit.dat", ios::in );
  if ( !inCredit ) {
     cerr << "File could not be opened." << endl;
     exit( 1 );
  }                                                 31
COUT << SETIOSFLAGS( IOS::LEFT ) << SETW( 10 ) <<
"ACCOUNT"




                                                           10/7/2012
    << SETW( 16 ) << "LAST NAME" << SETW( 11 )
    << "FIRST NAME" << RESETIOSFLAGS( IOS::LEFT )
    << SETW( 10 ) << "BALANCE" << ENDL;

     CLIENTDATA CLIENT;


     INCREDIT.READ( REINTERPRET_CAST<CHAR   *>( &CLIENT
),
             SIZEOF( CLIENTDATA )   );


                                                          32
WHILE        ( INCREDIT && !INCREDIT.EOF() ) {




                                                                   10/7/2012
        IF   ( CLIENT.ACCOUNTNUMBER != 0 )
             OUTPUTLINE( COUT, CLIENT );

        INCREDIT.READ( REINTERPRET_CAST<CHAR     *>( &CLIENT ),
                 SIZEOF( CLIENTDATA ) );
    }

    RETURN       0;
}



                                                                  33
10/7/2012
VOID OUTPUTLINE( OSTREAM   &OUTPUT, CONST CLIENTDATA &C )
{
    OUTPUT<< SETIOSFLAGS( IOS::LEFT ) << SETW( 10 )
       << C.ACCOUNTNUMBER << SETW( 16 ) << C.LASTNAME
       << SETW( 11 ) << C.FIRSTNAME << SETW( 10 )
       << SETPRECISION( 2 ) << RESETIOSFLAGS( IOS::LEFT )
       << SETIOSFLAGS( IOS::FIXED | IOS::SHOWPOINT )
       << C.BALANCE << 'N';
}



                                                            34
10/7/2012
THANK YOU…!!!



                35

Contenu connexe

Tendances

Gr8conf EU 2018 - Bring you infrastructure under control with Infrastructor
Gr8conf EU 2018 - Bring you infrastructure under control with InfrastructorGr8conf EU 2018 - Bring you infrastructure under control with Infrastructor
Gr8conf EU 2018 - Bring you infrastructure under control with InfrastructorStanislav Tiurikov
 
The first bug on Oracle Database 12c: how to create a pdb by cloning a remote...
The first bug on Oracle Database 12c: how to create a pdb by cloning a remote...The first bug on Oracle Database 12c: how to create a pdb by cloning a remote...
The first bug on Oracle Database 12c: how to create a pdb by cloning a remote...Marco Vigelini
 
Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBTobias Trelle
 
Oracle applications 11i hot backup cloning with rapid clone
Oracle applications 11i hot backup cloning with rapid cloneOracle applications 11i hot backup cloning with rapid clone
Oracle applications 11i hot backup cloning with rapid cloneDeepti Singh
 
Top 30 Node.js interview questions
Top 30 Node.js interview questionsTop 30 Node.js interview questions
Top 30 Node.js interview questionstechievarsity
 
Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBMongoDB
 
Oracle applications 11i hot backup cloning with rapid clone
Oracle applications 11i hot backup cloning with rapid cloneOracle applications 11i hot backup cloning with rapid clone
Oracle applications 11i hot backup cloning with rapid cloneDeepti Singh
 
MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know Norberto Leite
 
Webinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and MorphiaWebinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and MorphiaMongoDB
 
Simplifying Persistence for Java and MongoDB with Morphia
Simplifying Persistence for Java and MongoDB with MorphiaSimplifying Persistence for Java and MongoDB with Morphia
Simplifying Persistence for Java and MongoDB with MorphiaMongoDB
 
ATG Secure Repository
ATG Secure RepositoryATG Secure Repository
ATG Secure RepositorySanju Thomas
 
Symfony2 from the Trenches
Symfony2 from the TrenchesSymfony2 from the Trenches
Symfony2 from the TrenchesJonathan Wage
 
Top5 scalabilityissues withappendix
Top5 scalabilityissues withappendixTop5 scalabilityissues withappendix
Top5 scalabilityissues withappendixColdFusionConference
 
Custom YUI Widgets
Custom YUI WidgetsCustom YUI Widgets
Custom YUI Widgetscyrildoussin
 
eZ Publish cluster unleashed revisited
eZ Publish cluster unleashed revisitedeZ Publish cluster unleashed revisited
eZ Publish cluster unleashed revisitedBertrand Dunogier
 
Morphia, Spring Data & Co.
Morphia, Spring Data & Co.Morphia, Spring Data & Co.
Morphia, Spring Data & Co.Tobias Trelle
 
Redis学习笔记
Redis学习笔记Redis学习笔记
Redis学习笔记yongboy
 
Everybody Polyglot! - Cross-Language RPC with Erlang
Everybody Polyglot! - Cross-Language RPC with ErlangEverybody Polyglot! - Cross-Language RPC with Erlang
Everybody Polyglot! - Cross-Language RPC with ErlangRusty Klophaus
 

Tendances (20)

Gr8conf EU 2018 - Bring you infrastructure under control with Infrastructor
Gr8conf EU 2018 - Bring you infrastructure under control with InfrastructorGr8conf EU 2018 - Bring you infrastructure under control with Infrastructor
Gr8conf EU 2018 - Bring you infrastructure under control with Infrastructor
 
The first bug on Oracle Database 12c: how to create a pdb by cloning a remote...
The first bug on Oracle Database 12c: how to create a pdb by cloning a remote...The first bug on Oracle Database 12c: how to create a pdb by cloning a remote...
The first bug on Oracle Database 12c: how to create a pdb by cloning a remote...
 
Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDB
 
Oracle applications 11i hot backup cloning with rapid clone
Oracle applications 11i hot backup cloning with rapid cloneOracle applications 11i hot backup cloning with rapid clone
Oracle applications 11i hot backup cloning with rapid clone
 
Top 30 Node.js interview questions
Top 30 Node.js interview questionsTop 30 Node.js interview questions
Top 30 Node.js interview questions
 
Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDB
 
Oracle applications 11i hot backup cloning with rapid clone
Oracle applications 11i hot backup cloning with rapid cloneOracle applications 11i hot backup cloning with rapid clone
Oracle applications 11i hot backup cloning with rapid clone
 
MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know
 
Top5 scalabilityissues
Top5 scalabilityissuesTop5 scalabilityissues
Top5 scalabilityissues
 
2016-07-06-openphacts-docker
2016-07-06-openphacts-docker2016-07-06-openphacts-docker
2016-07-06-openphacts-docker
 
Webinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and MorphiaWebinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and Morphia
 
Simplifying Persistence for Java and MongoDB with Morphia
Simplifying Persistence for Java and MongoDB with MorphiaSimplifying Persistence for Java and MongoDB with Morphia
Simplifying Persistence for Java and MongoDB with Morphia
 
ATG Secure Repository
ATG Secure RepositoryATG Secure Repository
ATG Secure Repository
 
Symfony2 from the Trenches
Symfony2 from the TrenchesSymfony2 from the Trenches
Symfony2 from the Trenches
 
Top5 scalabilityissues withappendix
Top5 scalabilityissues withappendixTop5 scalabilityissues withappendix
Top5 scalabilityissues withappendix
 
Custom YUI Widgets
Custom YUI WidgetsCustom YUI Widgets
Custom YUI Widgets
 
eZ Publish cluster unleashed revisited
eZ Publish cluster unleashed revisitedeZ Publish cluster unleashed revisited
eZ Publish cluster unleashed revisited
 
Morphia, Spring Data & Co.
Morphia, Spring Data & Co.Morphia, Spring Data & Co.
Morphia, Spring Data & Co.
 
Redis学习笔记
Redis学习笔记Redis学习笔记
Redis学习笔记
 
Everybody Polyglot! - Cross-Language RPC with Erlang
Everybody Polyglot! - Cross-Language RPC with ErlangEverybody Polyglot! - Cross-Language RPC with Erlang
Everybody Polyglot! - Cross-Language RPC with Erlang
 

En vedette

Ebook En Sams Data Structures & Algorithms In Java
Ebook   En  Sams   Data Structures & Algorithms In JavaEbook   En  Sams   Data Structures & Algorithms In Java
Ebook En Sams Data Structures & Algorithms In JavaAldo Quelopana
 
Discrete Mathematics S. Lipschutz, M. Lipson And V. H. Patil
Discrete Mathematics S. Lipschutz, M. Lipson And V. H. PatilDiscrete Mathematics S. Lipschutz, M. Lipson And V. H. Patil
Discrete Mathematics S. Lipschutz, M. Lipson And V. H. Patilwidespreadpromotion
 
Data file handling in c++
Data file handling in c++Data file handling in c++
Data file handling in c++Vineeta Garg
 
2. Linear Data Structure Using Arrays - Data Structures using C++ by Varsha P...
2. Linear Data Structure Using Arrays - Data Structures using C++ by Varsha P...2. Linear Data Structure Using Arrays - Data Structures using C++ by Varsha P...
2. Linear Data Structure Using Arrays - Data Structures using C++ by Varsha P...widespreadpromotion
 
1. Fundamental Concept - Data Structures using C++ by Varsha Patil
1. Fundamental Concept - Data Structures using C++ by Varsha Patil1. Fundamental Concept - Data Structures using C++ by Varsha Patil
1. Fundamental Concept - Data Structures using C++ by Varsha Patilwidespreadpromotion
 
DATA STRUCTURES
DATA STRUCTURESDATA STRUCTURES
DATA STRUCTURESbca2010
 

En vedette (13)

GUI programming
GUI programmingGUI programming
GUI programming
 
File Pointers
File PointersFile Pointers
File Pointers
 
Ebook En Sams Data Structures & Algorithms In Java
Ebook   En  Sams   Data Structures & Algorithms In JavaEbook   En  Sams   Data Structures & Algorithms In Java
Ebook En Sams Data Structures & Algorithms In Java
 
Queues in C++
Queues in C++Queues in C++
Queues in C++
 
Discrete Mathematics S. Lipschutz, M. Lipson And V. H. Patil
Discrete Mathematics S. Lipschutz, M. Lipson And V. H. PatilDiscrete Mathematics S. Lipschutz, M. Lipson And V. H. Patil
Discrete Mathematics S. Lipschutz, M. Lipson And V. H. Patil
 
Stacks in c++
Stacks in c++Stacks in c++
Stacks in c++
 
Data file handling in c++
Data file handling in c++Data file handling in c++
Data file handling in c++
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
2. Linear Data Structure Using Arrays - Data Structures using C++ by Varsha P...
2. Linear Data Structure Using Arrays - Data Structures using C++ by Varsha P...2. Linear Data Structure Using Arrays - Data Structures using C++ by Varsha P...
2. Linear Data Structure Using Arrays - Data Structures using C++ by Varsha P...
 
1. Fundamental Concept - Data Structures using C++ by Varsha Patil
1. Fundamental Concept - Data Structures using C++ by Varsha Patil1. Fundamental Concept - Data Structures using C++ by Varsha Patil
1. Fundamental Concept - Data Structures using C++ by Varsha Patil
 
File Handling in C++
File Handling in C++File Handling in C++
File Handling in C++
 
DATA STRUCTURES
DATA STRUCTURESDATA STRUCTURES
DATA STRUCTURES
 
Data structures
Data structuresData structures
Data structures
 

Similaire à File handaling

Similaire à File handaling (20)

17 files and streams
17 files and streams17 files and streams
17 files and streams
 
File Handling
File HandlingFile Handling
File Handling
 
File Handling
File HandlingFile Handling
File Handling
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
 
file handling c++
file handling c++file handling c++
file handling c++
 
C++ files and streams
C++ files and streamsC++ files and streams
C++ files and streams
 
File in cpp 2016
File in cpp 2016 File in cpp 2016
File in cpp 2016
 
Pf cs102 programming-8 [file handling] (1)
Pf cs102 programming-8 [file handling] (1)Pf cs102 programming-8 [file handling] (1)
Pf cs102 programming-8 [file handling] (1)
 
working with files
working with filesworking with files
working with files
 
Files in c++
Files in c++Files in c++
Files in c++
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01
 
Build Automation of PHP Applications
Build Automation of PHP ApplicationsBuild Automation of PHP Applications
Build Automation of PHP Applications
 
Android | Busy Java Developers Guide to Android: Persistence | Ted Neward
Android | Busy Java Developers Guide to Android: Persistence | Ted NewardAndroid | Busy Java Developers Guide to Android: Persistence | Ted Neward
Android | Busy Java Developers Guide to Android: Persistence | Ted Neward
 
File operations
File operationsFile operations
File operations
 
File handling in cpp
File handling in cppFile handling in cpp
File handling in cpp
 
7 Data File Handling
7 Data File Handling7 Data File Handling
7 Data File Handling
 
File Management in C
File Management in CFile Management in C
File Management in C
 
DFSNov1.pptx
DFSNov1.pptxDFSNov1.pptx
DFSNov1.pptx
 
pointer, structure ,union and intro to file handling
 pointer, structure ,union and intro to file handling pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
 

Dernier

Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Association for Project Management
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 

Dernier (20)

Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 

File handaling

  • 1. 10/7/2012 FILE HANDALING 1 G.vishnuprabhu
  • 2. CONTENTS: 10/7/2012  File pointer and their manipulation  Sequential input and output operations  Adding content to a file 2
  • 4. HOW TO OPEN A FILE IN C++ ? 10/7/2012  #include<fstream.h>  ofstream streamname(“filename”, mode) or  Ofstream streamname; streamname.open(“filename”, mode) 4
  • 5. To create a file: #include<fstream.h> 10/7/2012 main() { fstream file(“newdoc.txt”); file.close(); } 5
  • 6. To write into a file: #include<fstream.h> 10/7/2012 main() { ofstream file(“newdoc.txt”); file<<“my first file handling program”; file.close(); } 6
  • 7. To close a file: The file is closed implicitly when a destructor for 10/7/2012 the corresponding object is called (Or) Obj.close() 7
  • 9. FILE POINTERS: 10/7/2012  The c++ input and output system manages two int value associates with a file  These are 1)get pointer 2)put pointer 9
  • 10. OPENING IN A FILE IN DIFFERENT MODES 10/7/2012 Read h e l l o w o r l d only Input pointer append h e l l o w o r l d Output pointer writing Output pointer 10
  • 11. 10/7/2012 Get pointer Put pointer  It specifies the location  It specifies the location in a file where the next in a file where the next read operation will write operation will occur occur 11
  • 12. FUNCTIONS 10/7/2012  tellg()  tellp()  seekg()  seekp() 12
  • 13. FILE POSITION POINTER 10/7/2012  <istream> and <ostream> classes provide member functions for repositioning the file pointer (the byte number of the next byte in the file to be read or to be written.)  These member functions are: seekg (seek get) for istream class seekp (seek put) for ostream class 13
  • 14. EXAMPLES OF MOVING A FILE POINTER 10/7/2012 obj.seekg(0) – repositions the file get pointer to the beginning of the file obj.seekg(0, ios:end) – repositions the file get pointer to the end of the file 14
  • 15. obj.seekg(n, ios:beg) – repositions the file get pointer to the n-th byte of the 10/7/2012 file obj.seekg(m, ios:end) – repositions the file get pointer to the m-th byte from the end of file The same operations can be performed with <ostream> function member seekp. 15
  • 16. MEMBER FUNCTIONS TELLG() AND TELLP(). 10/7/2012  Member functions tellg and tellp are provided to return the current locations of the get and put pointers, respectively.  long location = inClientFile.tellg();  To move the pointer relative to the current location use ios:cur  inClientFile.seekg(n, ios:cur) - moves the file get pointer n bytes forward. 16
  • 17. 10/7/2012 SEQUENTIAL INPUT AND OUTPUT OPERATIONS 17
  • 18. CREATING A SEQUENTIAL FILE 10/7/2012 // Create a sequential file #include <iostream.h> #include <fstream.h> #include <stdlib.h> int main() { // ofstream constructor opens file ofstream outClientFile( "clients.dat", ios::out ); if ( !outClientFile ) { // overloaded ! operator cerr << "File could not be opened" << endl; exit( 1 ); // prototype in stdlib.h } 18
  • 19. SEQUENTIAL FILE cout << "Enter the account, name, and balance.n" 10/7/2012 << "Enter end-of-file to end input.n? "; int account; char name[ 30 ]; float balance; while ( cin >> account >> name >> balance ) { outClientFile << account << ' ' << name << ' ' << balance << 'n'; cout << "? "; } return 0; // ofstream destructor closes file } 19
  • 20. UPDATING A SEQUENTIAL FILE 10/7/2012  Data that is formatted and written to a sequential file cannot be modified easily without the risk of destroying other data in the file.  If we want to modify a record of data, the new data may be longer than the old one and it could overwrite parts of the record following it. 20
  • 21. PROBLEMS WITH SEQUENTIAL FILES 10/7/2012  Sequential files are inappropriate for so-called “instant access” applications in which a particular record of information must be located immediately.  These applications include banking systems, point- of-sale systems, airline reservation systems, (or any data-base system.) 21
  • 22. RANDOM ACCESS FILES 10/7/2012  Instant access is possible with random access files.  Individual records of a random access file can be accessed directly (and quickly) without searching many other records. 22
  • 23. EXAMPLE OF A PROGRAM THAT CREATES A RANDOM ACCESS FILE 10/7/2012 // Definition of struct clientData used in // Figs. 14.11, 14.12, 14.14 and 14.15. #ifndef CLNTDATA_H #define CLNTDATA_H struct clientData { int accountNumber; char lastName[ 15 ]; char firstName[ 10 ]; float balance; }; #endif 23
  • 24. CREATING A RANDOM ACCESS FILE 10/7/2012 // Creating a randomly accessed file sequentially #include <iostream.h> #include <fstream.h> #include <stdlib.h> #include "clntdata.h" int main() { ofstream outCredit( "credit1.dat", ios::out); if ( !outCredit ) { cerr << "File could not be opened." << endl; exit( 1 ); } 24
  • 25. CLIENTDATA BLANKCLIENT = { 0, "", "", 0.0 }; 10/7/2012 FOR ( INT I = 0; I < 100; I++ ) OUTCREDIT.WRITE (REINTERPRET_CAST<CONST CHAR *>( &BLANKCLIENT ), SIZEOF( CLIENTDATA ) ); RETURN 0; } 25
  • 26. <OSTREAM> MEMEBR FUNCTION WRITE 10/7/2012  The <ostream> member function write outputs a fixed number of bytes beginning at a specific location in memory to the specific stream. When the stream is associated with a file, the data is written beginning at the location in the file specified by the “put” file pointer. 26
  • 27. THE WRITE FUNCTION EXPECTS A FIRST ARGUMENT OF TYPE CONST CHAR *, 10/7/2012 HENCE WE USED THE REINTERPRET_CAST <CONST CHAR *> TO CONVERT THE ADDRESS OF THE BLANKCLIENT TO A CONST CHAR *. THE SECOND ARGUMENT OF WRITE IS AN INTEGER OF TYPE SIZE_T SPECIFYING THE NUMBER OF BYTES TO WRITTEN. THUS THE SIZEOF( 27 CLIENTDATA ).
  • 28. WRITING DATA RANDOMLY TO A RANDOM FILE 10/7/2012 #include <iostream.h> #include <fstream.h> #include <stdlib.h> #include "clntdata.h" int main() { ofstream outCredit( "credit.dat", ios::ate ); if ( !outCredit ) { cerr << "File could not be opened." << endl; exit( 1 ); } 28
  • 29. 10/7/2012 COUT<< "ENTER ACCOUNT NUMBER " << "(1 TO 100, 0 TO END INPUT)N? "; CLIENTDATA CLIENT; CIN >> CLIENT.ACCOUNTNUMBER; WHILE ( CLIENT.ACCOUNTNUMBER > 0 && CLIENT.ACCOUNTNUMBER <= 100 ) { COUT << "ENTER LASTNAME, FIRSTNAME, BALANCEN? "; CIN >> CLIENT.LASTNAME >> CLIENT.FIRSTNAME >> CLIENT.BALANCE; 29
  • 30. OUTCREDIT.SEEKP( ( CLIENT.ACCOUNTNUMBER -1)* 10/7/2012 SIZEOF( CLIENTDATA ) ); OUTCREDIT.WRITE( REINTERPRET_CAST<CONST CHAR *>( &CLIENT ), SIZEOF( CLIENTDATA ) ); COUT << "ENTER ACCOUNT NUMBERN? "; CIN >> CLIENT.ACCOUNTNUMBER; } RETURN 0; } 30
  • 31. READING DATA FROM A RANDOM FILE 10/7/2012 #include <iostream.h> #include <iomanip.h> #include <fstream.h> #include <stdlib.h> #include "clntdata.h" void outputLine( ostream&, const clientData & ); int main() { ifstream inCredit( "credit.dat", ios::in ); if ( !inCredit ) { cerr << "File could not be opened." << endl; exit( 1 ); } 31
  • 32. COUT << SETIOSFLAGS( IOS::LEFT ) << SETW( 10 ) << "ACCOUNT" 10/7/2012 << SETW( 16 ) << "LAST NAME" << SETW( 11 ) << "FIRST NAME" << RESETIOSFLAGS( IOS::LEFT ) << SETW( 10 ) << "BALANCE" << ENDL; CLIENTDATA CLIENT; INCREDIT.READ( REINTERPRET_CAST<CHAR *>( &CLIENT ), SIZEOF( CLIENTDATA ) ); 32
  • 33. WHILE ( INCREDIT && !INCREDIT.EOF() ) { 10/7/2012 IF ( CLIENT.ACCOUNTNUMBER != 0 ) OUTPUTLINE( COUT, CLIENT ); INCREDIT.READ( REINTERPRET_CAST<CHAR *>( &CLIENT ), SIZEOF( CLIENTDATA ) ); } RETURN 0; } 33
  • 34. 10/7/2012 VOID OUTPUTLINE( OSTREAM &OUTPUT, CONST CLIENTDATA &C ) { OUTPUT<< SETIOSFLAGS( IOS::LEFT ) << SETW( 10 ) << C.ACCOUNTNUMBER << SETW( 16 ) << C.LASTNAME << SETW( 11 ) << C.FIRSTNAME << SETW( 10 ) << SETPRECISION( 2 ) << RESETIOSFLAGS( IOS::LEFT ) << SETIOSFLAGS( IOS::FIXED | IOS::SHOWPOINT ) << C.BALANCE << 'N'; } 34