SlideShare a Scribd company logo
Page 1 of 5
                                   Study Material for Class XII

                                          Data File Handling

Components of C++ to be used with file handling:
Header files: fstream.h
Classes: ifstream, ofstream, fstream
File modes: in, out, in out
Uses of cascaded operators ( << & >>) for writing text to the file and reading text from the file.
Functions like: open(), close(), get(), getline(), put(), tellg(), seekg(), tellp() and seekp()
Detecting end of files ( With or without using eof() function)
Opening a binary file using in, out and in out modes.

Header file: fstream.h         Classes : ifstream, ofstream and fstream
As we all know all system functions and tools in c++ is provided in a header file. For example
string.h file contains all system functions required for file handling such as strcmp(), strcpy() etc.
Like wise when we dealing with file handling all necessary functions have been clubbed together in
fstream.h header file.
‘fstream.h’ header file besides the other thing (classes and functions) contains three very important
classes. These classes are :
              ifstream : To open a data file in read only mode
              ofstream : To open a data file in write only mode
              fstream : To open a file in read/write mode
The last one fstream class is more flexible one but it increases the compiler overheads and
therefore it is always advised that we should use the most appropriate class for a data file to be
opened.
The following program opens a data file (a text file) and after reading its content displays on to the
monitor.
Progam#1 : Program for reading a file                Program#2 : Program for writing on to a file
#include <fsteam.h> // Using header file             #include <fsteam.h> // Using header file
void main()                                          void main()
{ ifstream aFile(“StName.txt”); // opening a         { ofstream aFile(“StName.txt”); // opening
file                                                 a
    char ch;                                                                                   file
    while(aFile.eof()) // checking for EOF             char ch;
    {    aFile.get(ch); // reading file                while(ch!=’*’) // checking for * to end
         cout<<ch; // displaying read data           data
    }                                                                        writing
    aFile.close();                                     {     ch=getch(); // reading file
}                                                            aFile.put(ch); // displaying read data
Note: Here ‘StName.txt’ is a text file containing       }
name of students that we are reading and                aFile.close();
displaying                                           }
                                                     Note: Here we are first reading a character
                                                     from the user and then writing on to the file
                                                     ‘StName.txt’

File Modes And opening a file with file modes: This is an information given at the time of
opening or creation of a file. It decides that what we can do with the file. In the above program it is
important to note that we have not mentioned that whether the file is to be opened in reading or
writing mode but the program runs successfully. This is because of the default file mode associated
with ifstream and ofstream classes respectfully. Following are the file modes used in C++:




                                         Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 2 of 5
        in : Read only mode. Used for reading purposes. This is default file mode for ‘ifstream’ class
with this mode an existing file is opened with all its data intact. But if the file doesn’t exist then a
blank file will be opened.
        out: Write only mode. Used for writing purposes. This is default file mode for ‘ofstream’
class. With this mode an existing file with same name is replaced with a new blank file and the
blank file is opened. In such a situation we will lost the old existing file. If the file doesn’t exit
straight way a new blank is opened.
        app: To append (add) data at the end of the file. This mode is used along with ‘out’ mode.
        ate: To fix the file pointer at the end the of file when it is opened. With this we write data
any where in the file even on the existing data by shifting the file pointer position.
        nocreate: To open only an existing file. This mode can be used along with both ‘in’ and ‘out’
modes.
        noreplace: To open only a non-existing file ( i.e. only a new file). This mode can be used
along with both ‘in’ and ‘out’ modes.
        trunc: With this mode all the data of the file is deleted and a blank file is opened.

From the above description of file modes we can also conclude that we can use one or more than
file modes when we create or open a file. In the above program file opening statements can also be
given as
Progam#1 : Program for reading a file              Program#2 : Program for writing on to a file
ifstream aFile(“StName.txt”, ios::in); //          ofstream aFile(“StName.txt”, ios::out); //
opening a                                          opening
                                              file
                                                   a file

Few examples of file opening statements:
    ifstream aFile(“StName.txt”);
      Here file mode is ‘ios::in’ which has been passed implicitly.
    ifstream aFile(“StName.txt”, ios::in);
      Here explicitly file mode ‘ios::in’ has been specified.
    ofstream X(“Story.dat”);
      Here file mode is ‘ios::out’ which has been passed implicitly. Here a new blank “Story.txt”
      file will be created and if it is already existing then all the data of the file will be lost.
    ofstream X(“Story.dat”,ios::out);
      Here file mode is ‘ios::out’ which has been passed explicitly. Here a new blank “Story.txt”
      file will be created and if it is already existing then all the data of the file will be lost.
    fstream X(“Story.dat”);
      This one is a wong Satement as we have not given the file mode. It is important to note
      that whenever we open or create a file with the help of fstream class we must always pass
      in, out or in out (both) file modes. i.e. there is no default file mode for the class fstream.
      Correct statement for the above will be as
      fstream X(“Story.dat”,ios::in||ios::out);        // Here we can both read from and write onto
      the file
    fstream X(“Story.dat”,ios::in||ios::nocreate);
      Here a “Story.dat” will be opened for reading but only when the file is existing.
    fstream X(“Story.dat”,ios::out||ios::noreplace);
      Here a new “Story.dat” will be opened for writing but only when the file is non-existing.
The entire above said concept works equally good for binary also.

Uses of cascaded operator (<< & >>) for reading and writing onto a text file:
Perhaps the easiest method to read and write from/to a file is with the help of cascaded ‘<<’
(insertion) and ‘>>’(extraction) operators.
     << : Used for writing onto the file
     >> : Used for reading from the file
The following shows how we use these two operators.

                                         Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 3 of 5

Progam#3 : Program for reading a file               Program#4 : Program for writing on to a file
#include <fstream.h>                                #include <fstream.h>
void main()                                         void main()
{                                                   {
  ifstream X(“MyFile.txt”); // Opening the file        ofstream X(“MyFile.txt”); // Creating the file
  char *s;                                             //Data writing on to the file
  while(!X.eof())                                      X<<”n A file pointer is an object that points
  { X>>s; // reading from the file                  to
      cout<<s; }                                         the particular location in the file.”
  X.close();                                           X<<” It is created with the help of the class
}                                                        fstream, ifstream and ofstream.”;
                                                       X.close();
                                                    }

Functions like: open(), close(), get(), getline(), put(), tellg(), seekg(), tellp() and
seekp()
Open(): This is member of all three classes we are using in file handling namely ifstream, of
stream and
fstream. We can open/create a file in ways. Either using the constructors or using the open()
function.
e.g. i) ifstream X(“Story.txt”); // This method uses a constructor of class ifstream to create the
file

    ii)     ifstream X;
           X.open(“Story.txt”); // This method uses member function open() of class ifstream to
create the
                                       file
close() : This one is also member of three classes namely ifstream, ofstream and fstream. This is
used to close a file.
e.g. ofstream X(“Story.txt”);
      …..
      X.close();
get(): This function is used to read a character from a file. It is member of ifstream class.
e.g. ifstream X(“Story.txt”);
      char ch;
      X.get(ch);
getline(): This is used for reading a line (string) from standard input device. This function receives
three parameters and their uses are as follows:
          First parameter is a storage variable name where the string is stored.
          Second parameter specifies the the length of the string to be read from the input buffer.
          Third parameter is a delimiting character that specifies that after this character no other
character from the input buffer will be read.
This function can also be used for reading from a file.
e.g. char *s;
       cin.getline(s,20,’*’);
       Case1      If we enter “We are Indians.” Then ‘s’ will store “We are Indians.”
       Case2      If we enter “We are*Indians.” Then ‘s’ will store “We are*”
       Case3      If we enter “We are Indians. And we are proud of it.” Then ‘s’ will store “We are
Indians. And “ ie 20 chars.
       Case4      If we enter “We are Indians. And we are proud*of it.” Then ‘s’ will store “We are
Indians. And “ ie 20 chars.
put(): This one is a member of ofstream class and is used for writing a single character on to a
file.
e.g. ofstream X(“Story.txt”);

                                         Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 4 of 5
    X.put(‘P’);

tellg(): It gives the current get-file pointer (read mode) position in a data file.
tellp(): It gives the current put-file pointer (write mode) position in a data file.

seekg(): This is used to shift get-file pointer position in a data file.
e.g. ifstream X(“Story.txt”);
    …….
    X.seekg(10);
    Here file pointer ‘X’ will be shifted 10 bytes in forward direction. To move the file pointer in
backward direction we pass a –ve no. This function receives one more parameter known as offset
that can be any of the three namely ios::beg, ios::end, and ios::cur.
      ios::beg : To move the pointer from the beginning of the file.
      ios::end : To move the pointer from the end of the file.
      ios::cur : To move the pointer from the current position of the file pointer.
e.g. X.seekg(10,ios::beg); 10 bytes form the beginning of the file.
seekp(): Same as above only that it works with put-file pointer and is a member of ‘ofstream’
class.

Detecting end of file with or without using eof() function:
A file pointer in a data file keeps on moving or changing its position with every read(get-file
pointer) or write(put-file pointer) operation. Following are the methods to find whether the file
pointer has reached to end of the file or not.
Program#5 : Detecting EOF with eof()                 Program#6 : Detecting EOF without eof()
#include <fsteam.h> // Using header file             #include <fstream.h> // Using header file
void main()                                          void main()
{ ifstream aFile(“StName.txt”); // opening a         { ifstream aFile(“StName.txt”); // opening a
file                                                 file
    char ch;                                             char ch;
    while(!aFile.eof()) // checking for EOF              while(aFile) // checking for EOF
    {    aFile.get(ch); // reading file                  {    aFile.get(ch); // reading file
         cout<<ch; // displaying read data                    cout<<ch; // displaying read data
    }                                                    }
    aFile.close();                                       aFile.close();
}                                                    }


In program#5 aFile.eof() returns true if aFile is at the EOF or false otherwise. And therefore we are
using ‘while (!aFile.eof())’ so that until and unless aFile is at EOF while loop will iterate. Here note
the ‘!’ operatetor.
In program#6 aFile returns false if aFile is at the EOF or true otherwise. And therefore we are using
‘while (aFile)’ so that until and unless aFile is at EOF while loop will iterate.




                                         Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 5 of 5
Questions:

Q1. Differentiate between the following
         a) ios::app and ios::ate b) ios::nocreate and ios::noreplace c) get() and put()
         d) ios::trunc and ios::out e) tellg() and seekg()
Q2. What is ‘file stream object’ or ‘file pointer’?
Q3. What is a stream?
Q4. Given the class definition
         class STOCK
         { int ITNO; char ITEM[10];
           public:
                 void GETIT() { cin>>ITNO; gets(ITEM); }
                 void SHOIT() { cout<<ITNO<<” “ <<ITEM <<endl; }
         };
Fill in the blanks for the following program:
Void read_obj()
{ ifstream X;
   X.open(“stock.dat”,___::out || __::in);
   If(!X)
      { cout<<”n Cannot open file”; exit(1); }
   STOCK sk;
     While(!X.____)
      {
          X.read( ( _____ )&sk,sizeof( _____ ));
           SHOWIT();
      }
    X.close();
}

Q5. Assuming that a text file named “FIRST.TXT” contains some text written into it, write a
function named vowelwords(), that reads the files FIRST.TXT and creates a new file named
SECOND.TXT, to contain only those words from the file FIRST.TXT which start with a lower case
vowel ( ie ‘a’,’e’,’i’,’o’ ,’u’). For example, if the file FIRST.TXT contains Carry umbrella and overcoat
when it rains Then the second file should contain umbrella and overcoat it
Hint: Here you have to read file first.txt word by word and check for the first character whether it
is lowercase vowel or not. If it is then you have to write word on to the file second.txt. For this
purpose you should use ‘>>’ operator for reading first.txt and ‘<<’ operator for writing on to the
file second.txt.

Q3. Write a c++ program to replace each space of text file “Books.dat” with ‘*’.
Hint: Here file has to be read character by character and if the character is a space then we have
to write on to the same place with ‘*’ character. For this purpose open the file in R/W mode. And
use seekg() or seekp() function properly to write on the correct place of the file.




                                          Prepared By Sumit Kumar Gupta, PGT Computer Science

More Related Content

PDF
File and directories in python
Lifna C.S
 
PPT
File handling(some slides only)
Kamlesh Nishad
 
PPT
Unit5 C
arnold 7490
 
PDF
Python programming : Files
Emertxe Information Technologies Pvt Ltd
 
PDF
Python - File operations & Data parsing
Felix Z. Hoffmann
 
PPTX
File handling in Python
Megha V
 
PPTX
File Handling and Command Line Arguments in C
Mahendra Yadav
 
PPTX
Data file handling in python reading & writing methods
keeeerty
 
File and directories in python
Lifna C.S
 
File handling(some slides only)
Kamlesh Nishad
 
Unit5 C
arnold 7490
 
Python programming : Files
Emertxe Information Technologies Pvt Ltd
 
Python - File operations & Data parsing
Felix Z. Hoffmann
 
File handling in Python
Megha V
 
File Handling and Command Line Arguments in C
Mahendra Yadav
 
Data file handling in python reading & writing methods
keeeerty
 

What's hot (19)

PPTX
Files and file objects (in Python)
PranavSB
 
PPTX
C Programming Unit-5
Vikram Nandini
 
PPT
File handling
Nilesh Dalvi
 
PDF
Python - Lecture 8
Ravi Kiran Khareedi
 
PPT
File handling in C++
Hitesh Kumar
 
PPTX
File handling in c
aakanksha s
 
PPT
File handling in_c
sanya6900
 
PPT
File handling in c
David Livingston J
 
PDF
Python file handling
Prof. Dr. K. Adisesha
 
PPTX
Data file handling
TAlha MAlik
 
PPSX
Files in c++
Selvin Josy Bai Somu
 
DOCX
File handling in c++
Daniel Nyagechi
 
PPTX
Files in php
sana mateen
 
PPTX
basics of file handling
pinkpreet_kaur
 
PPTX
Filesin c++
HalaiHansaika
 
PPTX
File Handling in C
Subhanshu Maurya
 
Files and file objects (in Python)
PranavSB
 
C Programming Unit-5
Vikram Nandini
 
File handling
Nilesh Dalvi
 
Python - Lecture 8
Ravi Kiran Khareedi
 
File handling in C++
Hitesh Kumar
 
File handling in c
aakanksha s
 
File handling in_c
sanya6900
 
File handling in c
David Livingston J
 
Python file handling
Prof. Dr. K. Adisesha
 
Data file handling
TAlha MAlik
 
Files in c++
Selvin Josy Bai Somu
 
File handling in c++
Daniel Nyagechi
 
Files in php
sana mateen
 
basics of file handling
pinkpreet_kaur
 
Filesin c++
HalaiHansaika
 
File Handling in C
Subhanshu Maurya
 
Ad

Viewers also liked (15)

PDF
Pointers
Swarup Kumar Boro
 
PDF
Computer science study material
Swarup Kumar Boro
 
PDF
Functions
Swarup Kumar Boro
 
PDF
2-D array
Swarup Kumar Boro
 
PDF
1-D array
Swarup Kumar Boro
 
PDF
01 computer communication and networks v
Swarup Kumar Boro
 
TXT
c++ program for Canteen management
Swarup Kumar Boro
 
PDF
Constructor & destructor
Swarup Kumar Boro
 
PDF
C++ revision tour
Swarup Kumar Boro
 
PDF
Implementation of oop concept in c++
Swarup Kumar Boro
 
TXT
c++ program for Railway reservation
Swarup Kumar Boro
 
PDF
Structures in c++
Swarup Kumar Boro
 
Computer science study material
Swarup Kumar Boro
 
01 computer communication and networks v
Swarup Kumar Boro
 
c++ program for Canteen management
Swarup Kumar Boro
 
Constructor & destructor
Swarup Kumar Boro
 
C++ revision tour
Swarup Kumar Boro
 
Implementation of oop concept in c++
Swarup Kumar Boro
 
c++ program for Railway reservation
Swarup Kumar Boro
 
Structures in c++
Swarup Kumar Boro
 
Ad

Similar to File handling (20)

PPT
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
Venugopalavarma Raja
 
PPTX
Unit-VI.pptx
Mehul Desai
 
PPTX
Cs1123 10 file operations
TAlha MAlik
 
PDF
chapter-12-data-file-handling.pdf
study material
 
PPTX
File management in C++
apoorvaverma33
 
PDF
Input File dalam C++
Teguh Nugraha
 
PDF
Data file handling
Prof. Dr. K. Adisesha
 
PPTX
Chapter4.pptx
WondimuBantihun1
 
PPT
7 Data File Handling
Praveen M Jigajinni
 
PPT
csc1201_lecture13.ppt
HEMAHEMS5
 
PDF
Filesinc 130512002619-phpapp01
Rex Joe
 
PPTX
INput output stream in ccP Full Detail.pptx
AssadLeo1
 
PDF
FILES IN C
yndaravind
 
PPTX
File Handling
AlgeronTongdoTopi
 
PPTX
File Handling
AlgeronTongdoTopi
 
PPTX
File handling in C hhsjsjshsjjsjsjs.pptx
armaansohail9356
 
PDF
DOC-20241121-WA0004bwushshusjssjuwh..pdf
TanishaWaichal
 
PPTX
File handling
Amber Wajid
 
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
Venugopalavarma Raja
 
Unit-VI.pptx
Mehul Desai
 
Cs1123 10 file operations
TAlha MAlik
 
chapter-12-data-file-handling.pdf
study material
 
File management in C++
apoorvaverma33
 
Input File dalam C++
Teguh Nugraha
 
Data file handling
Prof. Dr. K. Adisesha
 
Chapter4.pptx
WondimuBantihun1
 
7 Data File Handling
Praveen M Jigajinni
 
csc1201_lecture13.ppt
HEMAHEMS5
 
Filesinc 130512002619-phpapp01
Rex Joe
 
INput output stream in ccP Full Detail.pptx
AssadLeo1
 
FILES IN C
yndaravind
 
File Handling
AlgeronTongdoTopi
 
File Handling
AlgeronTongdoTopi
 
File handling in C hhsjsjshsjjsjsjs.pptx
armaansohail9356
 
DOC-20241121-WA0004bwushshusjssjuwh..pdf
TanishaWaichal
 
File handling
Amber Wajid
 

More from Swarup Kumar Boro (11)

PDF
Arrays and library functions
Swarup Kumar Boro
 
PDF
Function overloading
Swarup Kumar Boro
 
PDF
computer science sample papers 2
Swarup Kumar Boro
 
PDF
computer science sample papers 3
Swarup Kumar Boro
 
PDF
computer science sample papers 1
Swarup Kumar Boro
 
PDF
Boolean algebra
Swarup Kumar Boro
 
PDF
Boolean algebra laws
Swarup Kumar Boro
 
PDF
Oop basic concepts
Swarup Kumar Boro
 
DOCX
Physics
Swarup Kumar Boro
 
PPTX
Physics activity
Swarup Kumar Boro
 
Arrays and library functions
Swarup Kumar Boro
 
Function overloading
Swarup Kumar Boro
 
computer science sample papers 2
Swarup Kumar Boro
 
computer science sample papers 3
Swarup Kumar Boro
 
computer science sample papers 1
Swarup Kumar Boro
 
Boolean algebra
Swarup Kumar Boro
 
Boolean algebra laws
Swarup Kumar Boro
 
Oop basic concepts
Swarup Kumar Boro
 
Physics activity
Swarup Kumar Boro
 

Recently uploaded (20)

PPTX
Kanban Cards _ Mass Action in Odoo 18.2 - Odoo Slides
Celine George
 
PPTX
20250924 Navigating the Future: How to tell the difference between an emergen...
McGuinness Institute
 
PPTX
Continental Accounting in Odoo 18 - Odoo Slides
Celine George
 
PPTX
HEALTH CARE DELIVERY SYSTEM - UNIT 2 - GNM 3RD YEAR.pptx
Priyanshu Anand
 
PPTX
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
PPTX
CONCEPT OF CHILD CARE. pptx
AneetaSharma15
 
PPTX
A Smarter Way to Think About Choosing a College
Cyndy McDonald
 
PDF
The-Invisible-Living-World-Beyond-Our-Naked-Eye chapter 2.pdf/8th science cur...
Sandeep Swamy
 
PPTX
How to Close Subscription in Odoo 18 - Odoo Slides
Celine George
 
PPTX
BASICS IN COMPUTER APPLICATIONS - UNIT I
suganthim28
 
PPTX
Measures_of_location_-_Averages_and__percentiles_by_DR SURYA K.pptx
Surya Ganesh
 
PPTX
Gupta Art & Architecture Temple and Sculptures.pptx
Virag Sontakke
 
PPTX
family health care settings home visit - unit 6 - chn 1 - gnm 1st year.pptx
Priyanshu Anand
 
PPTX
Applications of matrices In Real Life_20250724_091307_0000.pptx
gehlotkrish03
 
PPTX
Tips Management in Odoo 18 POS - Odoo Slides
Celine George
 
PPTX
Basics and rules of probability with real-life uses
ravatkaran694
 
PPTX
How to Track Skills & Contracts Using Odoo 18 Employee
Celine George
 
PPTX
An introduction to Dialogue writing.pptx
drsiddhantnagine
 
PPTX
Artificial Intelligence in Gastroentrology: Advancements and Future Presprec...
AyanHossain
 
PPTX
Virus sequence retrieval from NCBI database
yamunaK13
 
Kanban Cards _ Mass Action in Odoo 18.2 - Odoo Slides
Celine George
 
20250924 Navigating the Future: How to tell the difference between an emergen...
McGuinness Institute
 
Continental Accounting in Odoo 18 - Odoo Slides
Celine George
 
HEALTH CARE DELIVERY SYSTEM - UNIT 2 - GNM 3RD YEAR.pptx
Priyanshu Anand
 
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
CONCEPT OF CHILD CARE. pptx
AneetaSharma15
 
A Smarter Way to Think About Choosing a College
Cyndy McDonald
 
The-Invisible-Living-World-Beyond-Our-Naked-Eye chapter 2.pdf/8th science cur...
Sandeep Swamy
 
How to Close Subscription in Odoo 18 - Odoo Slides
Celine George
 
BASICS IN COMPUTER APPLICATIONS - UNIT I
suganthim28
 
Measures_of_location_-_Averages_and__percentiles_by_DR SURYA K.pptx
Surya Ganesh
 
Gupta Art & Architecture Temple and Sculptures.pptx
Virag Sontakke
 
family health care settings home visit - unit 6 - chn 1 - gnm 1st year.pptx
Priyanshu Anand
 
Applications of matrices In Real Life_20250724_091307_0000.pptx
gehlotkrish03
 
Tips Management in Odoo 18 POS - Odoo Slides
Celine George
 
Basics and rules of probability with real-life uses
ravatkaran694
 
How to Track Skills & Contracts Using Odoo 18 Employee
Celine George
 
An introduction to Dialogue writing.pptx
drsiddhantnagine
 
Artificial Intelligence in Gastroentrology: Advancements and Future Presprec...
AyanHossain
 
Virus sequence retrieval from NCBI database
yamunaK13
 

File handling

  • 1. Page 1 of 5 Study Material for Class XII Data File Handling Components of C++ to be used with file handling: Header files: fstream.h Classes: ifstream, ofstream, fstream File modes: in, out, in out Uses of cascaded operators ( << & >>) for writing text to the file and reading text from the file. Functions like: open(), close(), get(), getline(), put(), tellg(), seekg(), tellp() and seekp() Detecting end of files ( With or without using eof() function) Opening a binary file using in, out and in out modes. Header file: fstream.h Classes : ifstream, ofstream and fstream As we all know all system functions and tools in c++ is provided in a header file. For example string.h file contains all system functions required for file handling such as strcmp(), strcpy() etc. Like wise when we dealing with file handling all necessary functions have been clubbed together in fstream.h header file. ‘fstream.h’ header file besides the other thing (classes and functions) contains three very important classes. These classes are :  ifstream : To open a data file in read only mode  ofstream : To open a data file in write only mode  fstream : To open a file in read/write mode The last one fstream class is more flexible one but it increases the compiler overheads and therefore it is always advised that we should use the most appropriate class for a data file to be opened. The following program opens a data file (a text file) and after reading its content displays on to the monitor. Progam#1 : Program for reading a file Program#2 : Program for writing on to a file #include <fsteam.h> // Using header file #include <fsteam.h> // Using header file void main() void main() { ifstream aFile(“StName.txt”); // opening a { ofstream aFile(“StName.txt”); // opening file a char ch; file while(aFile.eof()) // checking for EOF char ch; { aFile.get(ch); // reading file while(ch!=’*’) // checking for * to end cout<<ch; // displaying read data data } writing aFile.close(); { ch=getch(); // reading file } aFile.put(ch); // displaying read data Note: Here ‘StName.txt’ is a text file containing } name of students that we are reading and aFile.close(); displaying } Note: Here we are first reading a character from the user and then writing on to the file ‘StName.txt’ File Modes And opening a file with file modes: This is an information given at the time of opening or creation of a file. It decides that what we can do with the file. In the above program it is important to note that we have not mentioned that whether the file is to be opened in reading or writing mode but the program runs successfully. This is because of the default file mode associated with ifstream and ofstream classes respectfully. Following are the file modes used in C++: Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 2. Page 2 of 5 in : Read only mode. Used for reading purposes. This is default file mode for ‘ifstream’ class with this mode an existing file is opened with all its data intact. But if the file doesn’t exist then a blank file will be opened. out: Write only mode. Used for writing purposes. This is default file mode for ‘ofstream’ class. With this mode an existing file with same name is replaced with a new blank file and the blank file is opened. In such a situation we will lost the old existing file. If the file doesn’t exit straight way a new blank is opened. app: To append (add) data at the end of the file. This mode is used along with ‘out’ mode. ate: To fix the file pointer at the end the of file when it is opened. With this we write data any where in the file even on the existing data by shifting the file pointer position. nocreate: To open only an existing file. This mode can be used along with both ‘in’ and ‘out’ modes. noreplace: To open only a non-existing file ( i.e. only a new file). This mode can be used along with both ‘in’ and ‘out’ modes. trunc: With this mode all the data of the file is deleted and a blank file is opened. From the above description of file modes we can also conclude that we can use one or more than file modes when we create or open a file. In the above program file opening statements can also be given as Progam#1 : Program for reading a file Program#2 : Program for writing on to a file ifstream aFile(“StName.txt”, ios::in); // ofstream aFile(“StName.txt”, ios::out); // opening a opening file a file Few examples of file opening statements:  ifstream aFile(“StName.txt”); Here file mode is ‘ios::in’ which has been passed implicitly.  ifstream aFile(“StName.txt”, ios::in); Here explicitly file mode ‘ios::in’ has been specified.  ofstream X(“Story.dat”); Here file mode is ‘ios::out’ which has been passed implicitly. Here a new blank “Story.txt” file will be created and if it is already existing then all the data of the file will be lost.  ofstream X(“Story.dat”,ios::out); Here file mode is ‘ios::out’ which has been passed explicitly. Here a new blank “Story.txt” file will be created and if it is already existing then all the data of the file will be lost.  fstream X(“Story.dat”); This one is a wong Satement as we have not given the file mode. It is important to note that whenever we open or create a file with the help of fstream class we must always pass in, out or in out (both) file modes. i.e. there is no default file mode for the class fstream. Correct statement for the above will be as fstream X(“Story.dat”,ios::in||ios::out); // Here we can both read from and write onto the file  fstream X(“Story.dat”,ios::in||ios::nocreate); Here a “Story.dat” will be opened for reading but only when the file is existing.  fstream X(“Story.dat”,ios::out||ios::noreplace); Here a new “Story.dat” will be opened for writing but only when the file is non-existing. The entire above said concept works equally good for binary also. Uses of cascaded operator (<< & >>) for reading and writing onto a text file: Perhaps the easiest method to read and write from/to a file is with the help of cascaded ‘<<’ (insertion) and ‘>>’(extraction) operators.  << : Used for writing onto the file  >> : Used for reading from the file The following shows how we use these two operators. Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 3. Page 3 of 5 Progam#3 : Program for reading a file Program#4 : Program for writing on to a file #include <fstream.h> #include <fstream.h> void main() void main() { { ifstream X(“MyFile.txt”); // Opening the file ofstream X(“MyFile.txt”); // Creating the file char *s; //Data writing on to the file while(!X.eof()) X<<”n A file pointer is an object that points { X>>s; // reading from the file to cout<<s; } the particular location in the file.” X.close(); X<<” It is created with the help of the class } fstream, ifstream and ofstream.”; X.close(); } Functions like: open(), close(), get(), getline(), put(), tellg(), seekg(), tellp() and seekp() Open(): This is member of all three classes we are using in file handling namely ifstream, of stream and fstream. We can open/create a file in ways. Either using the constructors or using the open() function. e.g. i) ifstream X(“Story.txt”); // This method uses a constructor of class ifstream to create the file ii) ifstream X; X.open(“Story.txt”); // This method uses member function open() of class ifstream to create the file close() : This one is also member of three classes namely ifstream, ofstream and fstream. This is used to close a file. e.g. ofstream X(“Story.txt”); ….. X.close(); get(): This function is used to read a character from a file. It is member of ifstream class. e.g. ifstream X(“Story.txt”); char ch; X.get(ch); getline(): This is used for reading a line (string) from standard input device. This function receives three parameters and their uses are as follows: First parameter is a storage variable name where the string is stored. Second parameter specifies the the length of the string to be read from the input buffer. Third parameter is a delimiting character that specifies that after this character no other character from the input buffer will be read. This function can also be used for reading from a file. e.g. char *s; cin.getline(s,20,’*’); Case1 If we enter “We are Indians.” Then ‘s’ will store “We are Indians.” Case2 If we enter “We are*Indians.” Then ‘s’ will store “We are*” Case3 If we enter “We are Indians. And we are proud of it.” Then ‘s’ will store “We are Indians. And “ ie 20 chars. Case4 If we enter “We are Indians. And we are proud*of it.” Then ‘s’ will store “We are Indians. And “ ie 20 chars. put(): This one is a member of ofstream class and is used for writing a single character on to a file. e.g. ofstream X(“Story.txt”); Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 4. Page 4 of 5 X.put(‘P’); tellg(): It gives the current get-file pointer (read mode) position in a data file. tellp(): It gives the current put-file pointer (write mode) position in a data file. seekg(): This is used to shift get-file pointer position in a data file. e.g. ifstream X(“Story.txt”); ……. X.seekg(10); Here file pointer ‘X’ will be shifted 10 bytes in forward direction. To move the file pointer in backward direction we pass a –ve no. This function receives one more parameter known as offset that can be any of the three namely ios::beg, ios::end, and ios::cur. ios::beg : To move the pointer from the beginning of the file. ios::end : To move the pointer from the end of the file. ios::cur : To move the pointer from the current position of the file pointer. e.g. X.seekg(10,ios::beg); 10 bytes form the beginning of the file. seekp(): Same as above only that it works with put-file pointer and is a member of ‘ofstream’ class. Detecting end of file with or without using eof() function: A file pointer in a data file keeps on moving or changing its position with every read(get-file pointer) or write(put-file pointer) operation. Following are the methods to find whether the file pointer has reached to end of the file or not. Program#5 : Detecting EOF with eof() Program#6 : Detecting EOF without eof() #include <fsteam.h> // Using header file #include <fstream.h> // Using header file void main() void main() { ifstream aFile(“StName.txt”); // opening a { ifstream aFile(“StName.txt”); // opening a file file char ch; char ch; while(!aFile.eof()) // checking for EOF while(aFile) // checking for EOF { aFile.get(ch); // reading file { aFile.get(ch); // reading file cout<<ch; // displaying read data cout<<ch; // displaying read data } } aFile.close(); aFile.close(); } } In program#5 aFile.eof() returns true if aFile is at the EOF or false otherwise. And therefore we are using ‘while (!aFile.eof())’ so that until and unless aFile is at EOF while loop will iterate. Here note the ‘!’ operatetor. In program#6 aFile returns false if aFile is at the EOF or true otherwise. And therefore we are using ‘while (aFile)’ so that until and unless aFile is at EOF while loop will iterate. Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 5. Page 5 of 5 Questions: Q1. Differentiate between the following a) ios::app and ios::ate b) ios::nocreate and ios::noreplace c) get() and put() d) ios::trunc and ios::out e) tellg() and seekg() Q2. What is ‘file stream object’ or ‘file pointer’? Q3. What is a stream? Q4. Given the class definition class STOCK { int ITNO; char ITEM[10]; public: void GETIT() { cin>>ITNO; gets(ITEM); } void SHOIT() { cout<<ITNO<<” “ <<ITEM <<endl; } }; Fill in the blanks for the following program: Void read_obj() { ifstream X; X.open(“stock.dat”,___::out || __::in); If(!X) { cout<<”n Cannot open file”; exit(1); } STOCK sk; While(!X.____) { X.read( ( _____ )&sk,sizeof( _____ )); SHOWIT(); } X.close(); } Q5. Assuming that a text file named “FIRST.TXT” contains some text written into it, write a function named vowelwords(), that reads the files FIRST.TXT and creates a new file named SECOND.TXT, to contain only those words from the file FIRST.TXT which start with a lower case vowel ( ie ‘a’,’e’,’i’,’o’ ,’u’). For example, if the file FIRST.TXT contains Carry umbrella and overcoat when it rains Then the second file should contain umbrella and overcoat it Hint: Here you have to read file first.txt word by word and check for the first character whether it is lowercase vowel or not. If it is then you have to write word on to the file second.txt. For this purpose you should use ‘>>’ operator for reading first.txt and ‘<<’ operator for writing on to the file second.txt. Q3. Write a c++ program to replace each space of text file “Books.dat” with ‘*’. Hint: Here file has to be read character by character and if the character is a space then we have to write on to the same place with ‘*’ character. For this purpose open the file in R/W mode. And use seekg() or seekp() function properly to write on the correct place of the file. Prepared By Sumit Kumar Gupta, PGT Computer Science