Module 4
1. Write the C++ class hierarchy with diagram?
       In C++, a stream refers to a sequence of characters that are transferred between the program and
     input/output (I/O) devices. Stream classes in C++ facilitate input and output operations on files and
     other I/O devices. These classes have specific features to handle program input and output, making it
     easier to write portable code that can be used across multiple platforms.
     To use streams in C++, you need to include the appropriate header file. For instance, to use
     input/output streams, you would include the iostream header file. This library provides the necessary
     functions and classes to work with streams, enabling you to read and write data to and from files and
     other I/O devices.
     In this blog, we’ll be exploring four essential C++ stream classes:-
            istream
            ostream
            ifstream
            ofstream
Fig: I/O hierarchy
       This topic of file handling is further divided into sub-topics:
GMIT,AIML Dept.                         Introduction to C++ (BPLCK105D)                              Page 1
                      Create a file
                      Open a file
                      Read from a file
                      Write to a file
                      Close a file
    File Operations in C++
    C++ provides us with four different operations for file handling. They are:
           open() – This is used to create a file.
           read() – This is used to read the data from the file.
           write() – This is used to write new data to file.
           close() – This is used to close the file.
    2. Mention the possible ways to define the files?
        Files can be defined in 3 possible ways:
        ifstream<filename>------ (input file stream)-(read only)
        ofstream<filename>------(output file stream)-(write only)
        fstream<filename>-----I/O file stream)-(read/write only)
    3. Write the syntax for opening the file and explain with an example?
        Opening files in C++
                To read or enter data to a file, we need to open it first. This can be performed with the help
        of ‘ifstream’ for reading and ‘fstream’ or ‘ofstream’ for writing or appending to the file. All these
        three objects have open() function pre-built in them.
        Syntax:
        open( FileName , Mode );
        Here:
                 FileName – It denotes the name of file which has to be opened.
                 Mode – There different mode to open a file and it explained in this article.
GMIT,AIML Dept.                           Introduction to C++ (BPLCK105D)                               Page 2
                  Mode                        Description
                  iso::in                     File opened in reading mode
                  iso::out                    File opened in write mode
                  iso::app                    File opened in append mode
                                              File opened in append mode but read and write
                  iso::ate
                                              performed at the end of the file.
                  iso::binary                 File opened in binary mode
                  iso::trunc                  File opened in truncate mode
                  iso::nocreate               The file opens only if it exists
                  iso::noreplace              The file opens only if it doesn’t exist
      Example:-
        #include<iostream>
        #include<fstream>
        using namespace std;
        int main(){
          fstream FileName;
          FileName.open("FileName", ios::out);
          if (!FileName)
             {
            cout<<"Error while creating the file";
             }
          Else
             {
            cout<<"File created successfully";
            FileName.close();
GMIT,AIML Dept.                      Introduction to C++ (BPLCK105D)                          Page 3
                 }
            return 0;
        }
        Explanation of above code
                    Here we have an iostream library, which is responsible for input/output stream.
                    We also have a fstream library, which is responsible for handling files.
                    Creating an object of the fstream class and named it as ‘FileName’.
                    On the above-created object, we have to apply the open() function to create a new file,
                     and the mode is set to ‘out’ which will allow us to write into the file.
                    We use the ‘if’ statement to check for the file creation.
                    Prints the message to console if the file doesn’t exist.
                    Prints the message to console if the file exists/created.
                    We use the close() function on the object to close the file.
        Output
        File created successfully
    4. Write the syntax for Writing in to the file and explain with an example?
        Writing to File
        Till now, we learned how to create the file using C++. Now, we will learn how to write data to
        file which we created before. We will use fstream or ofstream object to write data into the file and
        to do so; we will use stream insertion operator (<<) along with the text enclosed within the
        double-quotes.
        With the help of open() function, we will create a new file named ‘FileName’ and then we will
        set the mode to ‘ios::out’ as we have to write the data to file.
        Syntax:
        FileName<<"Insert the text here";
        Program for Writing to File:
        #include<iostream>
        #include<fstream>
        using namespace std;
        int main()
                 {
GMIT,AIML Dept.                             Introduction to C++ (BPLCK105D)                            Page 4
                     fstream FileName;
                     FileName.open("FileName.txt", ios::out);
                     if (!FileName)
                            {
                                cout<<" Error while creating the file ";
                            }
                     else
                            {
                    cout<<"File created and data got written to file";
                    FileName<<"Hi good morning, best of luck ";
                    FileName.close();
            }
            return 0;
        }
        Explanation of above code
                     Here we have an iostream library, which is responsible for input/output stream.
                     We also have a fstream library, which is responsible for handling files.
                     Creating an object of the fstream class and named it as ‘FileName’.
                     On the above-created object, we have to apply the open() function to create a new file,
                      and the mode is set to ‘out’ which will allow us to write into the file.
                     We use the ‘if’ statement to check for the file creation.
                     Prints the message to console if the file doesn’t exist.
                     Prints the message to console if the file exists/created.
                     Writing the data to the created file.
                     We use the close() function on the object to close the file.
        Output
        File created and data got written to file
    5. Write the syntax for Reading from the file and explain with an example?
        Reading from file in C++
        Getting the data from the file is an essential thing to perform because without getting the data, we
        cannot perform any task. But don’t worry, C++ provides that option too. We can perform the
GMIT,AIML Dept.                                Introduction to C++ (BPLCK105D)                          Page 5
        reading of data from a file with the CIN to get data from the user, but then we use CIN to take
        inputs from the user’s standard console. Here we will use fstream or ifstream.
        Syntax:
        FileName>>Variable;
        Example:-
        #include<iostream>
        #include <fstream>
        using namespace std;
        int main() {
            fstream FileName;
            FileName.open("FileName.txt", ios::in);
            if (!FileName) {
                    cout<<"File doesn’t exist.";
            }
            else {
                    char x;
                    while (1) {
                        FileName>>x;
                        if(FileName.eof())
                          break;
                        cout<<x;
                    }
            }
            FileName.close();
            return 0;
        }
                       Explanation of above code
                       Here we have an iostream library, which is responsible for input/output stream.
                       We also have a fstream library which is responsible for handling files.
                       Creating an object of the fstream class and named it ‘FileName’.
GMIT,AIML Dept.                               Introduction to C++ (BPLCK105D)                             Page 6
                On the above-created object, we have to apply the open() function to create a new file,
                 and the mode is set to ‘in’ which will allow us to read from the file.
                We use the ‘if’ statement to check for the file creation.
                Prints the message to console if the file doesn’t exist.
                Creating a character(char) variable with the named x.
                Iterating of the file with the help of while loop.
                Getting the file data to the variable x.
                Here we are using if condition with eof() which stands for the end of the file to tell the
                 compiler to read till the file’s end.
                We use the ‘break’ statement to stop the reading from file when it reaches the end.
                The print statement to print the content that is available in the variable x.
                We use the close() function on the object to close the file
        Output
        Hello World,
    6. Write the syntax for closing the file and explain with an example?
        Closing a file in C++
        Closing a file is a good practice, and it is must to close the file. Whenever the C++ program
        comes to an end, it clears the allocated memory, and it closes the file. We can perform the task
        with the help of close() function.
        Syntax:
        FileName.close();
        Program to Close a File:
        #include <iostream>
        #include <fstream>
        using namespace std;
        int main() {
          fstream FileName;
          FileName.open("FileName.txt", ios::in);
          if (!FileName) {
GMIT,AIML Dept.                          Introduction to C++ (BPLCK105D)                               Page 7
                    cout<<"File doesn’t exist";
            }
            else {
                    cout<<"File opened successfully";
                    }
            }
            FileName.close();
            return 0;
        }
        Explanation of above code
                       Here we have an iostream library, which is responsible for input/output stream.
                       We also have a fstream library, which is responsible for handling files.
                       Creating an object of the fstream class and named it as ‘FileName’.
                       On the above-created object, we will apply the open() function to create a new file, and
                        the mode is set to ‘out’ which allows us to write into the file.
                       We use the ‘if’ statement to check for the file creation.
                       Prints the message to console if the file doesn’t exist.
                       Prints the message to console if the file opened or not.
                       We use the close() function on the object to close the file.
    7. Write the C++ program to read a few lines and then display each word in a different line?
        #include <iostream>
        #include <fstream>
        #include<string>
        using namespace std;
        int main()
        {
                    String Inputline, Outputline;
                    ofstream Obj1(“xyz.txt”);
                    cout<<”input:”<<endl;
                    while(1)
                             {
GMIT,AIML Dept.                                Introduction to C++ (BPLCK105D)                             Page 8
                                Cin>>Inputline;
                                If(Inputline==”END”)
                                Break;
                                Obj1<<Inputline<<endl;//writing to the file
                       }
                Obj1.close();
                Cout<<”output:”;
                ifstream Obj2(“xyz.txt”);
                while(!obj2.eof())
                       {
                                Obj2>>Outputline<<endl;
                                Cout<<Outputline<<”/n”;
                       }
                Obj2.close();
                Return 0;
        }
        INPUT:
        It was a Fight
        For pride and ego
        For one
        It was a fight for
        duty and self-respect for another
        who won it at the end END
        OUTPUT:
        It
        Was
        A
        Fight
        …….
        ……
        ……
        Who
GMIT,AIML Dept.                          Introduction to C++ (BPLCK105D)      Page 9
        Won
        It
        at
        the
        end.
    8. Write the C++ program to read a few lines and then display line using unformatted I/O
        methods ie get() and put()?
        #include <iostream>
        #include <fstream>
        #include<string>
        using namespace std;
        int main()
        {
               char ch;
               ofstream Obj1(“xyz.txt”);
               while(1)
                      {
                               Cin.get(ch);
                               If(ch==”$”)
                               Break;
                               Obj1<<ch<<endl;//writing to the file
                      }
               Obj1.close();
               ifstream Obj2(“xyz.txt”);
               while(!obj2.eof())
                      {
                               Obj2>>Outputline<<endl;
                               Cout<<Outputline<<”/n”;
                      }
               Obj2.close();
               Return 0;
GMIT,AIML Dept.                         Introduction to C++ (BPLCK105D)                Page 10
        }
             Input:
             The Battle
             Between x and y
             Is
             Between light and dark
             Output:
             The Battle
             Between x and y
             Is
             Between light and dark
    9. Write the C++ program to read a few lines and then display line using unformatted I/O
        methods ie getline()?
        #include <iostream>
        #include <fstream>
        #include<string>
        using namespace std;
        int main()
        {
             char a[80],b[80];
             ofstream obj1(“xyz.txt”);
             while(1)
             {
                      cin.getline(a,80);
                      if(!strcmp(a,”end”))
                      break;
                      obj1<<a<<endl;
             }
             obj1.close();
             ifstream obj2(“xyz.txt”);
             while(!obj2.eof())
GMIT,AIML Dept.                        Introduction to C++ (BPLCK105D)                 Page 11
                  {
                         obj2.getline(b,80);
                         cout<<b<<endl;
                  }
                  obj2.close();
      return 0;
      }
      Input:
      Imagination is
      More important
      Than Knowledge
      end
      Out put:
      Imagination is more important that knowledge.
    10. What is binary files?
                  Binary File Handling is a process in which we create a file and store data in its original
          format. It means that if we stored an integer value in a binary file, the value will be treated as an
          integer rather than text.
                  Binary files are mainly used for storing records just as we store records in a database. It
          makes it easier to access or modify the records easily.
    11. Write the syntax for opening the binary file?
          A file stream object can be opened in one of two ways. First, you can supply a file name along
          with an i/o mode parameter to the constructor when declaring an object:
            ifstream myFile ("file name.txt", ios::in | ios::binary);
          Alternatively, after a file stream object has been declared, you can call its open method:
            ofstream myFile;
            ...
            myFile.open ("filename.txt", ios::out | ios::binary);
    12. Write the syntax for reading and writing the binary file?
          Two member functions for ifstream and ofstream objects are useful in reading and writing both of
          them have similar syntax.
GMIT,AIML Dept.                           Introduction to C++ (BPLCK105D)                                Page 12
        They are
        1. Writing in the file
        ofstream obj.write((char *) &<the Object>, sizeof(<the same object>));
        2. Reading from the file
        ifstream obj.read((char *) &<the object>,sizeof(<the same object>));
    13. Write the syntax for closing the binary file?
        Closing the binary file is similar to the closing if the text file,
        FileObject.close();
    14. Write the C++ program for writing to the binary file?
             #include<iostream>
             #include<fstream>
             using namespace std;
             struct student
             {
                      int Rollno;
                      char Name[30];
                      char Address[30];
             };
             void abc(student &s)
             {
                      cout<<”Enter the Rollnumber:”;
                      cin>>s.Rollno;
                      cout<<”Enter the Name:”;
                      cin>>s.Name;
                      cout<<”Enter the Address:”;
                      cin>>s.Address;
             }
             int main()
             {
                      struct student obj1;
                      ofstream obj2;
                      obj2.open(“xyz.txt”, ios::out|ios::binary|ios::trunc);
                      if(!obj2)
GMIT,AIML Dept.                         Introduction to C++ (BPLCK105D)          Page 13
                       {
                              Cout<<”file can not be created\n”;
                       }
                       char con=’y’;
                       do
                       {
                              abc(obj1):
                              obj2.write((char*) &obj1,sizeof(struct student));
                              if(obj2.fail())
                              {
                                       cout<<”file write failed\n”;
                              }
                              cout<<”do you want to continue?(y/n):”;
                              cin>>con;
                       }
                       while(con!=’n’);
                       obj2.close();
                       return 0;
               }
      Input:
      Enter Rollno:1
      Enter name:abc
      Enter Address:xyz
      do you want to continue?(y/n);y
      Enter Rollno:2
      Enter name:abcd
      Enter Address:wxyz
      do you want to continue?(y/n);n
      Output:
      Checking the xyz.txt file in C drive
GMIT,AIML Dept.                           Introduction to C++ (BPLCK105D)         Page 14
    15. Write the C++ program for Reading in to the binary file?
            #include<iostream>
            #include<fstream>
            using namespace std;
            struct student
            {
                   int Rollno;
                   char Name[30];
                   char Address[30];
            };
            void xyz(student s)
            {
                   cout<<”Enter the Rollnumber:”;
                   cin>>s.Rollno;
                   cout<<”Enter the Name:”;
                   cin>>s.Name;
                   cout<<”Enter the Address:”;
                   cin>>s.Address;
            }
            int main()
            {
                   struct student obj1;
                   ofstream obj2;
                   while(!obj2.eof())
                   {
GMIT,AIML Dept.                      Introduction to C++ (BPLCK105D)   Page 15
                              obj2.read((char *) &obj1,sizeof(struct student));
                              if(obj2.fail())
                              break;
                       }
                       xyz(obj1);
                       obj2.close();
               return 0;
               }
      Input:
      Enter Rollno:1
      Enter name:abc
      Enter Address:xyz
      Enter Rollno:2
      Enter name:abcd
      Enter Address:wxyz
GMIT,AIML Dept.                         Introduction to C++ (BPLCK105D)           Page 16