SlideShare a Scribd company logo
1 of 48
Lecture 12
             Classes and
                Files



TCP1231 Computer Programming I   1
Objectives

   To learn about classes and files
   Explore how to declare and manipulate classes.
   To illustrate the usage of classes with arrays,
    structure, and functions.
   To learn how to use text and binary files




   TCP1231 Computer Programming I        2
Classes




TCP1231 Computer Programming I   3
Classes
A class is a logical method to organize data and functions in the
same structure. They are declared using keyword class, whose
functionality is similar to that of the C++ keyword struct, but
with the possibility of including functions as members, instead
of only data.

  class class_name
  {
      permission_label_1:
              member1;
      permission_label_2:
              member2;
          ...
  } object_name;




   TCP1231 Computer Programming I                 4
Classes
 where class_name is a name for the class (user defined type) and the
 optional field object_name is one, or several, valid object
 identifiers. The body of the declaration can contain members, that
 can be either data or function declarations, and optionally
 permission labels, that can be any of these three keywords:
 private:, public: or protected:. They make reference to the
 permission which the following members acquire:
• private members of a class are accessible only from other members
  of their same class or from their "friend" classes.
• protected members are accessible from members of their same
  class and friend classes, and also from members of their derived
  classes.
• public members are accessible from anywhere the class is visible.
      TCP1231 Computer Programming I               5
Example 1
            class student{
                    int a;
                    char b;
                    int f1(int );
            private:
                    int c;
                    float d;
                    void f2(int, int);
            protected:
                    int e;
                    string addr;
                    float f3(float, char);
            public:
                    int g;
                    string name;
                    void f4(int, int, string);
                    int f5(int, float, char);
             };

   TCP1231 Computer Programming I                6
Example 2
                                     class A declares 3
 class A{                            variables
   public:                           •i is public to all users
     int i;                          of class A

   protected:                        •j is protected, can

     int j;                          only be used by
                                     methods in class A or
   private:                          its derived classes

     int k;                          •k is private, can only

 };                                  be used by methods in
                                     class A.

    TCP1231 Computer Programming I              7
Classes
 If we declare members of a class before including any permission label, the
 members are considered private, since it is the default permission that the
 members of a class declared with the class keyword acquire
                        class CRectangle
                        {
                                 int x, y;
                           public:
                                 void set_values (int,int);
                                 int area (void);
                        } rect;


Declares class CRectangle and an object called rect of this class (type). This
class contains four members: two variables of type int (x and y) in the private
section (because private is the default permission) and two functions in the public
section: set_values() and area(), of which we have only included the prototype.
Notice the difference between class name and object name: In the previous
example, CRectangle was the class name, whereas rect was an object of type
CRectangle.
       TCP1231 Computer Programming I                 8
#include <iostream>                      #include <iostream>
using namespace std;                     using namespace std;

struct info {                            class info {
                                           public:
     int id;                                 int id;
     float avg;                              float avg;
     string name;                            string name;
};                                       };

int main () {                            int main () {
  info s1;                                 info c1;
  s1.id=204;                               c1.id=204;
  s1.avg=84.8;                             c1.avg=84.8;
  s1.name=“qdah";                          c1.name=“qdah";

    system(“pause”);                         system(“pause”);
    return 0;                                return 0;
}                                        }




        TCP1231 Computer Programming I               9
#include <iostream>                       #include <iostream>
using namespace std;                      using namespace std;

struct info {                             class info {
     int id;                              public:
     int avg;                                 int id;
     string name;                             int avg;
};                                            string name;
info read()                                   void read() {
{                                                 cin >> id;
      info data;                                  cin >> avg;
    cin >> data.id;                               cin >> name;
    cin >> data.avg;                          }
    cin >> data.name;                     };
    return data;                          int main () {
}                                           info c1;
int main () {                               c1.read();
  info s1;
  s1=read ();                                 return 0;
                                          }
    return 0;
}

         TCP1231 Computer Programming I                   10
#include <iostream>                       #include <iostream>
using namespace std;                      using namespace std;

class info {                              class info {
    int id;                                   int id;
    int avg;                                  int avg;
    string name;                              string name;
public:                                   public:
    void read() {                             void read();
        cin >> id;                        };
        cin >> avg;                       void info:: read(){
        cin >> name;                              cin >> id;
    }                                             cin >> avg;
};                                                cin >> name;
int main () {                             };
  info c1;                                int main () {
  c1.read();                                info c1;
                                            c1.read();
    return 0;
}                                             return 0;
                                          }


         TCP1231 Computer Programming I                   11
#include <iostream>
using namespace std;

class CRectangle {
      int x, y;
  public:
     void set_values (int,int);
     int area (void) {return (x*y);}
};
void CRectangle::set_values (int a, int b) {
  x = a;
  y = b;
}

int main () {
  CRectangle rect;
  rect.set_values (3,4);
  cout << "area: " << rect.area();
  return 0;                                    area: 12
}



   TCP1231 Computer Programming I              12
#include <iostream>
using namespace std;

class CRectangle {
      int x, y;
  public:
     void set_values (int,int);
     int area (void) {return (x*y);}
};
void CRectangle::set_values (int a, int b) {
  x = a;
  y = b;
}

int main () {
  CRectangle rect, rectb;                           rect area: 12
  rect.set_values (3,4);                            rectb area: 30
  rectb.set_values (5,6);
  cout << "rect area: " << rect.area() << endl;
  cout << "rectb area: " << rectb.area() << endl;
}


   TCP1231 Computer Programming I                   13
Constructors and Destructors
Objects generally need to initialize variables or assign dynamic
memory during their process of creation to become totally operative
and to avoid returning unexpected values during their execution.
For example, what would happen if in the previous example we
called the function area() before having called function set_values?
Probably an indetermined result since the members x and y would
have never been assigned a value.
In order to avoid that, a class can include a special function: a
constructor, which can be declared by naming a member function
with the same name as the class. This constructor function will be
called automatically when a new instance of the class is created
(when declaring a new object or allocating an object of that class)
and only then. We are going to implement CRectangle including a
constructor:
      TCP1231 Computer Programming I               14
#include <iostream>
using namespace std;                                Example  Constructor
class CRectangle {
   int width, height;
  public:
   CRectangle () { width = 0; height = 0;};
   CRectangle (int,int);
   int area (void) {return (width*height);}
};
CRectangle::CRectangle (int a, int b) {
  width = a;
  height = b;
}

int main () {
  CRectangle rect (3,4);
  CRectangle rectb (5,6);                               rect area: 12
  CRectangle rectc;                                     rectb area: 30
  cout << "rect area: " << rect.area() << endl;
  cout << "rectb area: " << rectb.area() << endl;       rectc area: 0
  cout << "rectc area: " << rectc.area() << endl;
}
       TCP1231 Computer Programming I                      15
#include <iostream>
using namespace std;                                  Example 
class CRectangle {                                    Constructor & Destructors
   int *width, *height;
  public:
   CRectangle (int,int);
                                                              rect area: 12
   ~CRectangle ();                                            rectb area: 30
   int area (void) {return (*width * *height);}
};

CRectangle::CRectangle (int a, int b) {      CRectangle::~CRectangle () {
  width = new int;                             delete width;
  height = new int;                            delete height;
  *width = a;                                }
  *height = b;
}                                  int main () {
                                     CRectangle rect (3,4), rectb (5,6);
                                     cout << "rect area: " << rect.area()
                                          << endl;
                                     cout << "rectb area: " << rectb.area()
                                          << endl;
                                     return 0;
                                   }
         TCP1231 Computer Programming I                    16
#include <iostream>                    Point readPoint()
#include <math.h>                      {
using namespace std;                     Point p;
struct Point                               cout<< "enter point x,y : ";
{ int x;                                   cin>> p.x >> p.y;
   int y;                                  return p;
};                                     }
void printPoint(Point );
float distPoint(Point , Point );       void printPoint(Point p)
Point readPoint();                     {
                                          cout<< "(x = "<< p.x<< ", y = "<<
int main(){                               p.y<<")"<< endl;
  Point p1, p2;                        }
  float d;
  p1=readPoint(); cout<< "p1 = ";      float distPoint(Point p, Point q)
  printPoint(p1);                      {
  p2=readPoint(); cout<< "p2 = ";        float dx = p.x - q.x;
  printPoint(p2);                        float dy = p.y - q.y;
  d= distPoint(p1,p2);                   float dsquared = dx*dx + dy*dy;
  cout<< "distance p1 to p2 = "<< d;
  d= distPoint(p2,p1);                     return sqrt(dsquared);
  cout<< "distance p2 to p1 = "<< d;   }
  return 0;}
         TCP1231 Computer Programming I                       17
#include <iostream>                                 int main()
#include <math.h>                                   {
using namespace std;                                  Point p1, p2;
class Point{                                          float d;
   private:
         int x;                                         p1.readPoint();
         int y;                                         cout<< "p1 = ";
   public:                                              p1.printPoint();
     void readPoint();                                  cout<< endl;
     void printPoint();                                 p2.readPoint();
     float distPoint(Point q);                          cout<< "p2 = ";
};                                                      p2.printPoint();
void Point::readPoint(){                                cout<< endl;
 cout<< "enter point x,y : ";
  cin>> x >> y;                                         d = p1.distPoint(p2);
}                                                       cout<< "distance p1 to p2 = “ << d
void Point::printPoint(){                                     << endl;
cout<< "(x = "<< x<< ", y = "<< y <<")"<< endl; }       d= p2.distPoint(p1);
float Point::distPoint(Point q){                        cout<< "distance p2 to p1 = "<< d
  float dx = x - q.x;                                       << endl<< endl;
  float dy = y - q.y;
  float dsquared = dx*dx + dy*dy;                       system("pause");
  return sqrt(dsquared);                                return 0;
}         TCP1231 Computer Programming I            }              18
Files




TCP1231 Computer Programming I   19
Streams and Basic File I/O
• Files for I/O are the same type of files used to
  store programs

• A stream is a flow of data.
  – Input stream: Data flows into the program
      • If input stream flows from keyboard, the program
        will accept data from the keyboard
      • If input stream flows from a file, the program will
        accept data from the file
  – Output stream: Data flows out of the program
      • To the screen
      • To a file

    TCP1231 Computer Programming I           20
Standard I/O

 • cin – the standard input stream
 • cout – the standard output stream
 • cerr – the standard error stream

 These streams are automatically created for you when
 your program executes. To use them you only need to
 #include <iostream> and the appropriate using directives.




  TCP1231 Computer Programming I           21
Why use Files?
• Files allow you to store data permanently!
• Data output to a file lasts after the program ends
• An input file can be used over and over
   – No typing of data again and again for testing
• Create a data file or read an output file at your
  convenience
• Files allow you to deal with larger data sets




   TCP1231 Computer Programming I           22
File I/O
When a program takes input from a file, we say that
it reads from the file.

When a program puts data into a file, we say that
it writes to the file.

To read or write to a file, we create a stream object,
and connect it to the file.




    TCP1231 Computer Programming I       23
File I/O
• Reading from a file
   – Taking input from a file
   – Done from beginning to the end
      • No backing up to read something again
      • Just as done from the keyboard

• Writing to a file
  – Sending output to a file
  – Done from beginning to end
     • No backing up to write something again
     • Just as done to the screen


    TCP1231 Computer Programming I        24
More on Files
       Files are used for permanent storage of data.
       Files are stored on secondary storage devices such as
        magnetic disks, optical disks and tapes.
                Bit:        smallest data items in a computer ( 0 or 1)
                Byte:       Sequence of Bits (8 Bits)
          C++ views each file simple as a sequence of bytes.
           Each file ends with an end-of-file marker
           When a file is opened, an object is created and a
           stream is associated with the object.

       0   1    2   3   4     5   6   7     …      n-1

                                            …            End-of-file
                                                         marker


   TCP1231 Computer Programming I                            25
Input/Output with files
 C++ has support both for input and output with files
 through the following classes:
 ifstream: File class for reading operations (derived from istream)
 ofstream: File class for writing operations (derived from ostream)
 fstream: File class for both reading and writing operations
  (derived from iostream)
                             #include <fstream>
                             using namespace std;
                             int main()
                             {
                                ofstream outfile("myfile1.dat");
                                ifstream infile ("myfile2.dat");
                                fstream iofile ("myfile3.dat");

     TCP1231 Computer Programming I                    26
Input-file Stream (ifstream)
• Input-file streams are of type ifstream

• Type ifstream is defined in the fstream library
   – You must use the include and using directives
                 #include <fstream>
                 using namespace std;

• Declare an input-file stream variable using
                ifstream in_stream;




    TCP1231 Computer Programming I          27
Output-file Stream (ofstream)
• Output-file streams of are type ofstream

• Type ofstream is defined in the fstream library
   – You must use these include and using directives
                 #include <fstream>
                 using namespace std;

• Declare an input-file stream variable using
                ofstream out_stream;




    TCP1231 Computer Programming I           28
The fstreams Classes
We use objects of the ifstream class to read from
a file, and objects of the ofstream class to write to
a file.

These classes are defined in <fstream>. To use them
we must write

  #include <fstream>
  using std::ifstream;
  using std::ofstream;


   TCP1231 Computer Programming I      29
Connecting To a File

• Once a stream variable is declared, connect it to
  a file
   – Connecting a stream to a file is opening the file
   – Use the open function of the stream object

                     in_stream.open("infile.dat");

                                               Double quotes
                             Period
                                    File name on the disk

   TCP1231 Computer Programming I             30
How to open files?
To open a file with a stream object we use the function open()
                        void open ( filename, mode);
filename is a string of characters representing the name of the file
to be opened and mode is a combination of the following flags:
           ios::in         Open file for reading
           ios::out        Open file for writing
           ios::ate        Initial position: end of file
           ios::app        Every output is appended at the end of file
           ios::trunc      If the file already existed it is erased
           ios::binary     Binary mode

              ofstream file;
OR            file.open (“file1.abc", ios::out | ios::app | ios::binary);

         ofstream file (“file1.abc", ios::out | ios::app | ios::binary);
     TCP1231 Computer Programming I                             31
More processes
To check if the file has been correctly opened we use is_open()
that returns a bool type value indicating True in case that indeed
the object has been correctly associated with an open file or False
otherwise

 After we finish using the file we must close it, to do that the
 function close() is used.
 After we call close(), the stream object can be used to open
 another file, and the file is available again to be opened by other
 processes
                                  Files
This for test                                                 !
“Hi and Bye”                                            îyÑå▌┘┬µα╣
                                                           ÜÑå«ìæ
                Text Files               Binary Files

     TCP1231 Computer Programming I                32
Closing A File
• After using a file, it should be closed
  – This disconnects the stream from the file
  – Close files to reduce the chance of a file being
    corrupted if the program terminates abnormally

• It is important to close an output file if your
  program later needs to read input
  from the output file

• The system will automatically close files if you
  forget as long as your program ends normally



     TCP1231 Computer Programming I           33
Example




  TCP1231 Computer Programming I   34
Text Files
We use the same members of classes that we used in communication
with the console (cin and cout). As in the following example, where
we use the overloaded insertion operator <<
#include <fstream>                            #include <iostream>
using namespace std;                          #include <fstream>
                                              using namespace std;
int main () { // writing to a text file       int main () { // reading a text file
 ofstream myfile ("file1.txt“, ios::out);      char buffer;
 if (myfile.is_open())                         ifstream myfile ("file1.txt“, ios::in);
 {                                             if (! myfile.is_open())
   myfile << “Message from Belal.n";          { cout << "Error"; exit (1); }
   myfile << “Just Hi and Bye.";
   myfile.put(‘n’);                           while (! myfile.eof() ) {
   myfile.close();                               myfile.get (buffer);
 }                                               cout << buffer;
                                               }
 return 0;                                     return 0;
}                                             }
 eof() TCP1231true if a file opened for reading has reached the end
         Returns Computer Programming I                       35
Text Files                  Read from a file “in.dat” then
                            Write to a file “out.dat”
     #include <fstream>
     #include <iostream>
     using namespace std;
     int main()
     {
          char ch;

         ifstream infile("IN.DAT");
         ofstream outfile("OUT.DAT");
         while (infile)
              {
              infile.get(ch);
              outfile.put(ch);
         }
              infile.close();
     }

   TCP1231 Computer Programming I                    36
The End of The File
• Input files used by a program may vary in length
   – Programs may not be able to assume the number
     of items in the file

• A way to know the end of the file is reached:
  – The boolean expression (in_stream >> next)
     • Reads a value from in_stream and stores it in next
     • True if a value can be read and stored in next
     • False if there is not a value to be read




    TCP1231 Computer Programming I         37
End of The File - Example
• To calculate the average of the numbers in a file
   –           double next, sum = 0;
           int count = 0;
           while(in_stream >> next)
        {
           sum = sum + next;
               count++;
           }

             double average = sum / count;


   TCP1231 Computer Programming I            38
Binary Files
 When we introduced C++ I/O, we said that input and output
 streams converted between the programs internal representation
 for data objects and characters (such as from the internal
 representation for the number 15 to the characters ‘1’ and ‘5’ and
 vice versa)
 Reason for doing this:
 To translate between the internal binary representation and a
 format that is easier to understand for humans.

 Thus, C++ allows us to perform binary file I/O, in which we store
 and retrieve the original binary representation for data objects



    TCP1231 Computer Programming I               39
Binary Files
   The advantages of binary file are:
    No need to convert between the internal representation and
     a character-based representation
    Reduces the associated time to store/retrieve data
    Possible conversion and round-off errors are avoided
    Storing data objects in binary format usually takes less
     space (though this depends on the nature of the data)
   Disadvantages:
    The file is not easily readable by humans
    Portability becomes an issue, as different operating
     systems (and even different compilers) may use different
     internal representations

   TCP1231 Computer Programming I              40
Creating Binary Files
To open a file with a stream object we use the function open()
            void open ( filename, mode | ios::binary);

 Creating   a stream that will handle binary I/O is as simple
 as setting a flag
 Create a binary file output stream:

      ofstream fout (“myFile.txt”, ios::out |ios::trunc | ios::binary);

 Create   a binary file input stream:
             ifstream fin (“myFile2.txt”, ios::in | ios::binary);




    TCP1231 Computer Programming I                           41
Binary Files (read and write)
Two functions are used : READ & WRITE
write()
    –Lets us write a specified number of characters to an output
    stream
    –does a straight byte-by-byte copy
        fout.write(reinterpret_cast<char *>(&obj), sizeof obj);

read ( )
    –Lets us read a specified number of characters to an output
    stream
    –does a straight byte-by-byte read
        fin.read(reinterpret_cast<char *>(&obj), sizeof obj);

    TCP1231 Computer Programming I                42
Example
#include <iostream>           ofstream output;
#include <fstream>            output.open("indata.dat", ios::out|ios::binary);
#include <cstring>            output.write(reinterpret_cast<char *>(&people),
using namespace std;                  sizeof(person) );
                              output.close();
typedef struct
 { char gender;               person newperson;
    int age;                  ifstream input;
    string name;              input.open("indata.dat", ios::in|ios::binary);
  } person;                   input.read(reinterpret_cast<char *> (&newperson),
                                     sizeof(person) );
int main(void)                cout << "n Name is ==> " << newperson.name;
{                             cout << "n Gender is ==> " << newperson.gender;
    person people;            cout << "n Age is ==> " << newperson.age;
    people.name= "Ali";       input.close();
    people.age= 22;
    people.gender= 'm';       return 0;
                          }
       TCP1231 Computer Programming I                       43
File Seek
The C++ I/O system supports four functions for seeking
 seekg()            ifstream           Moves get file pointer to a specific location
 seekp()            ofstream           Moves put file pointer to a specific location

 tellg()            ifstream           Returns the current position of the get pointer
 tellp()            ofstream           Returns the current position of the put pointer
                                                     moves the file pointer to the 20th byte in
  Origin value     Seek From …                       the file, infile. After this, if a read
  ios::beg         seek from beginning of file       operation is initiated, the reading starts
  ios::cur         seek from current location        from the 21st item within the file.
  ios::end         seek from end of file

                                                               moves the file pointer to the
infile.seekg(20, ios::beg);   or infile.seekg(20);             20th byte in the file outfile.
                                                               After this, if write operation is
outfile.seekp(20, ios::beg); or outfile.seekp(20);             initiated, the writing starts
                                                               from the 21st item within the
                                                               file.

           TCP1231 Computer Programming I                          44
Seek

Seek call                            Action performed

outfile.seekg(0, ios::beg)    Go to the beginning of the file
outfile.seekg(0, ios::cur)    Stay at the current file
outfile.seekg(0, ios::end)    Go to the end of the file
outfile.seekg(n, ios::beg)    Move to (n+1) byte location in the file
outfile.seekg(n, ios::cur)    Move forward by n bytes from current position
outfile.seekg(-n, ios::cur)   Move backward by n bytes from current position
outfile.seekg(-n, ios::end)   Move forward by n bytes from the end
infile.seekg(n, ios::beg)     Move write pointer to (n+1) byte location
infile.seekg(-n, ios::cur)    Move write pointer backward by n bytes




    TCP1231 Computer Programming I                         45
Examples,,, seekp, tellp
              ofstream fout(“myFile.txt”);
              if (fout.is_open()) {
                 fout << “Hello, this is a file.” << endl;
                  fout.seekp(15);
                  fout << “not a file“;

      ofstream fout(“myFile.txt”);
      if (fout.is_open() ) {
         fout << “Hello,this is a file.” << endl;
         fout.seekp(fout.tellp()– static_cast<streampos>(8));
         fout << “not a file“;

              ofstream fout(“myFile.txt”);
              if (fout.is_open()) {
                   fout << “Hello, this is a file.” << endl;
                   fout.seekp(-8, ios_base::cur);
                   fout << “not a file“;

    TCP1231 Computer Programming I                             46
Examples,,, seekg, tellg
                    ifstream fin(“myFile.txt”);
                    if (fin.is_open()) {
                      char c;
                      fin.seekg(5, ios_base::cur);
                      fin >> c;
                    …
                    }


            ifstream fin(“myFile.txt”);
            if (fin.is_open() ) {
              char c;
              fin.seekg(fin.tellg()–static_cast<streampos>(5) );
              fin >> c;
            …
            }


    TCP1231 Computer Programming I                        47
The End




TCP1231 Computer Programming I   48

More Related Content

What's hot

C aptitude.2doc
C aptitude.2docC aptitude.2doc
C aptitude.2docSrikanth
 
FP 201 - Unit 6
FP 201 - Unit 6FP 201 - Unit 6
FP 201 - Unit 6rohassanie
 
Cs1123 8 functions
Cs1123 8 functionsCs1123 8 functions
Cs1123 8 functionsTAlha MAlik
 
FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2rohassanie
 
User defined functions
User defined functionsUser defined functions
User defined functionsshubham_jangid
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to pythonMarian Marinov
 
Pydiomatic
PydiomaticPydiomatic
Pydiomaticrik0
 
Computer science-2010-cbse-question-paper
Computer science-2010-cbse-question-paperComputer science-2010-cbse-question-paper
Computer science-2010-cbse-question-paperDeepak Singh
 
Python programing
Python programingPython programing
Python programinghamzagame
 
Recursion to iteration automation.
Recursion to iteration automation.Recursion to iteration automation.
Recursion to iteration automation.Russell Childs
 
Chapter 7 functions (c)
Chapter 7 functions (c)Chapter 7 functions (c)
Chapter 7 functions (c)hhliu
 
Learning C++ - Pointers in c++ 2
Learning C++ - Pointers in c++ 2Learning C++ - Pointers in c++ 2
Learning C++ - Pointers in c++ 2Ali Aminian
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processingIntro C# Book
 

What's hot (20)

Fp201 unit4
Fp201 unit4Fp201 unit4
Fp201 unit4
 
Captitude 2doc-100627004318-phpapp01
Captitude 2doc-100627004318-phpapp01Captitude 2doc-100627004318-phpapp01
Captitude 2doc-100627004318-phpapp01
 
C aptitude.2doc
C aptitude.2docC aptitude.2doc
C aptitude.2doc
 
FP 201 - Unit 6
FP 201 - Unit 6FP 201 - Unit 6
FP 201 - Unit 6
 
Fp201 unit5 1
Fp201 unit5 1Fp201 unit5 1
Fp201 unit5 1
 
Advanced C - Part 2
Advanced C - Part 2Advanced C - Part 2
Advanced C - Part 2
 
Cs1123 8 functions
Cs1123 8 functionsCs1123 8 functions
Cs1123 8 functions
 
FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2
 
User defined functions
User defined functionsUser defined functions
User defined functions
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Pointers
PointersPointers
Pointers
 
Pydiomatic
PydiomaticPydiomatic
Pydiomatic
 
Computer science-2010-cbse-question-paper
Computer science-2010-cbse-question-paperComputer science-2010-cbse-question-paper
Computer science-2010-cbse-question-paper
 
Python programing
Python programingPython programing
Python programing
 
Recursion to iteration automation.
Recursion to iteration automation.Recursion to iteration automation.
Recursion to iteration automation.
 
C++ Pointers
C++ PointersC++ Pointers
C++ Pointers
 
Chapter 7 functions (c)
Chapter 7 functions (c)Chapter 7 functions (c)
Chapter 7 functions (c)
 
Chapter 2 Java Methods
Chapter 2 Java MethodsChapter 2 Java Methods
Chapter 2 Java Methods
 
Learning C++ - Pointers in c++ 2
Learning C++ - Pointers in c++ 2Learning C++ - Pointers in c++ 2
Learning C++ - Pointers in c++ 2
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processing
 

Similar to Lecture 12: Classes and Files

Classes and object
Classes and objectClasses and object
Classes and objectAnkit Dubey
 
Constructor in c++
Constructor in c++Constructor in c++
Constructor in c++Jay Patel
 
class and objects
class and objectsclass and objects
class and objectsPayel Guria
 
Lecture02 class -_templatev2
Lecture02 class -_templatev2Lecture02 class -_templatev2
Lecture02 class -_templatev2Hariz Mustafa
 
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13Abu Saleh
 
3 functions and class
3   functions and class3   functions and class
3 functions and classtrixiacruz
 
More on Classes and Objects
More on Classes and ObjectsMore on Classes and Objects
More on Classes and ObjectsPayel Guria
 
Multiple file programs, inheritance, templates
Multiple file programs, inheritance, templatesMultiple file programs, inheritance, templates
Multiple file programs, inheritance, templatesSyed Zaid Irshad
 
Object oriented programming using c++
Object oriented programming using c++Object oriented programming using c++
Object oriented programming using c++Hoang Nguyen
 
Object oriented programming 2
Object oriented programming 2Object oriented programming 2
Object oriented programming 2Aadil Ansari
 

Similar to Lecture 12: Classes and Files (20)

Classes and object
Classes and objectClasses and object
Classes and object
 
Constructor in c++
Constructor in c++Constructor in c++
Constructor in c++
 
Ds lab handouts
Ds lab handoutsDs lab handouts
Ds lab handouts
 
class and objects
class and objectsclass and objects
class and objects
 
Lecture02 class -_templatev2
Lecture02 class -_templatev2Lecture02 class -_templatev2
Lecture02 class -_templatev2
 
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
 
Lecture18
Lecture18Lecture18
Lecture18
 
Bc0037
Bc0037Bc0037
Bc0037
 
OOC MODULE1.pptx
OOC MODULE1.pptxOOC MODULE1.pptx
OOC MODULE1.pptx
 
Basic c#
Basic c#Basic c#
Basic c#
 
3 functions and class
3   functions and class3   functions and class
3 functions and class
 
C++ via C#
C++ via C#C++ via C#
C++ via C#
 
Lecture5
Lecture5Lecture5
Lecture5
 
Oop objects_classes
Oop objects_classesOop objects_classes
Oop objects_classes
 
More on Classes and Objects
More on Classes and ObjectsMore on Classes and Objects
More on Classes and Objects
 
Codejunk Ignitesd
Codejunk IgnitesdCodejunk Ignitesd
Codejunk Ignitesd
 
OOPS 22-23 (1).pptx
OOPS 22-23 (1).pptxOOPS 22-23 (1).pptx
OOPS 22-23 (1).pptx
 
Multiple file programs, inheritance, templates
Multiple file programs, inheritance, templatesMultiple file programs, inheritance, templates
Multiple file programs, inheritance, templates
 
Object oriented programming using c++
Object oriented programming using c++Object oriented programming using c++
Object oriented programming using c++
 
Object oriented programming 2
Object oriented programming 2Object oriented programming 2
Object oriented programming 2
 

Recently uploaded

Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.arsicmarija21
 

Recently uploaded (20)

Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.
 

Lecture 12: Classes and Files

  • 1. Lecture 12 Classes and Files TCP1231 Computer Programming I 1
  • 2. Objectives To learn about classes and files Explore how to declare and manipulate classes. To illustrate the usage of classes with arrays, structure, and functions. To learn how to use text and binary files TCP1231 Computer Programming I 2
  • 4. Classes A class is a logical method to organize data and functions in the same structure. They are declared using keyword class, whose functionality is similar to that of the C++ keyword struct, but with the possibility of including functions as members, instead of only data. class class_name { permission_label_1: member1; permission_label_2: member2; ... } object_name; TCP1231 Computer Programming I 4
  • 5. Classes where class_name is a name for the class (user defined type) and the optional field object_name is one, or several, valid object identifiers. The body of the declaration can contain members, that can be either data or function declarations, and optionally permission labels, that can be any of these three keywords: private:, public: or protected:. They make reference to the permission which the following members acquire: • private members of a class are accessible only from other members of their same class or from their "friend" classes. • protected members are accessible from members of their same class and friend classes, and also from members of their derived classes. • public members are accessible from anywhere the class is visible. TCP1231 Computer Programming I 5
  • 6. Example 1 class student{ int a; char b; int f1(int ); private: int c; float d; void f2(int, int); protected: int e; string addr; float f3(float, char); public: int g; string name; void f4(int, int, string); int f5(int, float, char); }; TCP1231 Computer Programming I 6
  • 7. Example 2 class A declares 3 class A{ variables public: •i is public to all users int i; of class A protected: •j is protected, can int j; only be used by methods in class A or private: its derived classes int k; •k is private, can only }; be used by methods in class A. TCP1231 Computer Programming I 7
  • 8. Classes If we declare members of a class before including any permission label, the members are considered private, since it is the default permission that the members of a class declared with the class keyword acquire class CRectangle { int x, y; public: void set_values (int,int); int area (void); } rect; Declares class CRectangle and an object called rect of this class (type). This class contains four members: two variables of type int (x and y) in the private section (because private is the default permission) and two functions in the public section: set_values() and area(), of which we have only included the prototype. Notice the difference between class name and object name: In the previous example, CRectangle was the class name, whereas rect was an object of type CRectangle. TCP1231 Computer Programming I 8
  • 9. #include <iostream> #include <iostream> using namespace std; using namespace std; struct info { class info { public: int id; int id; float avg; float avg; string name; string name; }; }; int main () { int main () { info s1; info c1; s1.id=204; c1.id=204; s1.avg=84.8; c1.avg=84.8; s1.name=“qdah"; c1.name=“qdah"; system(“pause”); system(“pause”); return 0; return 0; } } TCP1231 Computer Programming I 9
  • 10. #include <iostream> #include <iostream> using namespace std; using namespace std; struct info { class info { int id; public: int avg; int id; string name; int avg; }; string name; info read() void read() { { cin >> id; info data; cin >> avg; cin >> data.id; cin >> name; cin >> data.avg; } cin >> data.name; }; return data; int main () { } info c1; int main () { c1.read(); info s1; s1=read (); return 0; } return 0; } TCP1231 Computer Programming I 10
  • 11. #include <iostream> #include <iostream> using namespace std; using namespace std; class info { class info { int id; int id; int avg; int avg; string name; string name; public: public: void read() { void read(); cin >> id; }; cin >> avg; void info:: read(){ cin >> name; cin >> id; } cin >> avg; }; cin >> name; int main () { }; info c1; int main () { c1.read(); info c1; c1.read(); return 0; } return 0; } TCP1231 Computer Programming I 11
  • 12. #include <iostream> using namespace std; class CRectangle { int x, y; public: void set_values (int,int); int area (void) {return (x*y);} }; void CRectangle::set_values (int a, int b) { x = a; y = b; } int main () { CRectangle rect; rect.set_values (3,4); cout << "area: " << rect.area(); return 0; area: 12 } TCP1231 Computer Programming I 12
  • 13. #include <iostream> using namespace std; class CRectangle { int x, y; public: void set_values (int,int); int area (void) {return (x*y);} }; void CRectangle::set_values (int a, int b) { x = a; y = b; } int main () { CRectangle rect, rectb; rect area: 12 rect.set_values (3,4); rectb area: 30 rectb.set_values (5,6); cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl; } TCP1231 Computer Programming I 13
  • 14. Constructors and Destructors Objects generally need to initialize variables or assign dynamic memory during their process of creation to become totally operative and to avoid returning unexpected values during their execution. For example, what would happen if in the previous example we called the function area() before having called function set_values? Probably an indetermined result since the members x and y would have never been assigned a value. In order to avoid that, a class can include a special function: a constructor, which can be declared by naming a member function with the same name as the class. This constructor function will be called automatically when a new instance of the class is created (when declaring a new object or allocating an object of that class) and only then. We are going to implement CRectangle including a constructor: TCP1231 Computer Programming I 14
  • 15. #include <iostream> using namespace std; Example  Constructor class CRectangle { int width, height; public: CRectangle () { width = 0; height = 0;}; CRectangle (int,int); int area (void) {return (width*height);} }; CRectangle::CRectangle (int a, int b) { width = a; height = b; } int main () { CRectangle rect (3,4); CRectangle rectb (5,6); rect area: 12 CRectangle rectc; rectb area: 30 cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl; rectc area: 0 cout << "rectc area: " << rectc.area() << endl; } TCP1231 Computer Programming I 15
  • 16. #include <iostream> using namespace std; Example  class CRectangle { Constructor & Destructors int *width, *height; public: CRectangle (int,int); rect area: 12 ~CRectangle (); rectb area: 30 int area (void) {return (*width * *height);} }; CRectangle::CRectangle (int a, int b) { CRectangle::~CRectangle () { width = new int; delete width; height = new int; delete height; *width = a; } *height = b; } int main () { CRectangle rect (3,4), rectb (5,6); cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl; return 0; } TCP1231 Computer Programming I 16
  • 17. #include <iostream> Point readPoint() #include <math.h> { using namespace std; Point p; struct Point cout<< "enter point x,y : "; { int x; cin>> p.x >> p.y; int y; return p; }; } void printPoint(Point ); float distPoint(Point , Point ); void printPoint(Point p) Point readPoint(); { cout<< "(x = "<< p.x<< ", y = "<< int main(){ p.y<<")"<< endl; Point p1, p2; } float d; p1=readPoint(); cout<< "p1 = "; float distPoint(Point p, Point q) printPoint(p1); { p2=readPoint(); cout<< "p2 = "; float dx = p.x - q.x; printPoint(p2); float dy = p.y - q.y; d= distPoint(p1,p2); float dsquared = dx*dx + dy*dy; cout<< "distance p1 to p2 = "<< d; d= distPoint(p2,p1); return sqrt(dsquared); cout<< "distance p2 to p1 = "<< d; } return 0;} TCP1231 Computer Programming I 17
  • 18. #include <iostream> int main() #include <math.h> { using namespace std; Point p1, p2; class Point{ float d; private: int x; p1.readPoint(); int y; cout<< "p1 = "; public: p1.printPoint(); void readPoint(); cout<< endl; void printPoint(); p2.readPoint(); float distPoint(Point q); cout<< "p2 = "; }; p2.printPoint(); void Point::readPoint(){ cout<< endl; cout<< "enter point x,y : "; cin>> x >> y; d = p1.distPoint(p2); } cout<< "distance p1 to p2 = “ << d void Point::printPoint(){ << endl; cout<< "(x = "<< x<< ", y = "<< y <<")"<< endl; } d= p2.distPoint(p1); float Point::distPoint(Point q){ cout<< "distance p2 to p1 = "<< d float dx = x - q.x; << endl<< endl; float dy = y - q.y; float dsquared = dx*dx + dy*dy; system("pause"); return sqrt(dsquared); return 0; } TCP1231 Computer Programming I } 18
  • 20. Streams and Basic File I/O • Files for I/O are the same type of files used to store programs • A stream is a flow of data. – Input stream: Data flows into the program • If input stream flows from keyboard, the program will accept data from the keyboard • If input stream flows from a file, the program will accept data from the file – Output stream: Data flows out of the program • To the screen • To a file TCP1231 Computer Programming I 20
  • 21. Standard I/O • cin – the standard input stream • cout – the standard output stream • cerr – the standard error stream These streams are automatically created for you when your program executes. To use them you only need to #include <iostream> and the appropriate using directives. TCP1231 Computer Programming I 21
  • 22. Why use Files? • Files allow you to store data permanently! • Data output to a file lasts after the program ends • An input file can be used over and over – No typing of data again and again for testing • Create a data file or read an output file at your convenience • Files allow you to deal with larger data sets TCP1231 Computer Programming I 22
  • 23. File I/O When a program takes input from a file, we say that it reads from the file. When a program puts data into a file, we say that it writes to the file. To read or write to a file, we create a stream object, and connect it to the file. TCP1231 Computer Programming I 23
  • 24. File I/O • Reading from a file – Taking input from a file – Done from beginning to the end • No backing up to read something again • Just as done from the keyboard • Writing to a file – Sending output to a file – Done from beginning to end • No backing up to write something again • Just as done to the screen TCP1231 Computer Programming I 24
  • 25. More on Files  Files are used for permanent storage of data.  Files are stored on secondary storage devices such as magnetic disks, optical disks and tapes. Bit: smallest data items in a computer ( 0 or 1) Byte: Sequence of Bits (8 Bits)  C++ views each file simple as a sequence of bytes.  Each file ends with an end-of-file marker  When a file is opened, an object is created and a stream is associated with the object. 0 1 2 3 4 5 6 7 … n-1 … End-of-file marker TCP1231 Computer Programming I 25
  • 26. Input/Output with files C++ has support both for input and output with files through the following classes:  ifstream: File class for reading operations (derived from istream)  ofstream: File class for writing operations (derived from ostream)  fstream: File class for both reading and writing operations (derived from iostream) #include <fstream> using namespace std; int main() { ofstream outfile("myfile1.dat"); ifstream infile ("myfile2.dat"); fstream iofile ("myfile3.dat"); TCP1231 Computer Programming I 26
  • 27. Input-file Stream (ifstream) • Input-file streams are of type ifstream • Type ifstream is defined in the fstream library – You must use the include and using directives #include <fstream> using namespace std; • Declare an input-file stream variable using ifstream in_stream; TCP1231 Computer Programming I 27
  • 28. Output-file Stream (ofstream) • Output-file streams of are type ofstream • Type ofstream is defined in the fstream library – You must use these include and using directives #include <fstream> using namespace std; • Declare an input-file stream variable using ofstream out_stream; TCP1231 Computer Programming I 28
  • 29. The fstreams Classes We use objects of the ifstream class to read from a file, and objects of the ofstream class to write to a file. These classes are defined in <fstream>. To use them we must write #include <fstream> using std::ifstream; using std::ofstream; TCP1231 Computer Programming I 29
  • 30. Connecting To a File • Once a stream variable is declared, connect it to a file – Connecting a stream to a file is opening the file – Use the open function of the stream object in_stream.open("infile.dat"); Double quotes Period File name on the disk TCP1231 Computer Programming I 30
  • 31. How to open files? To open a file with a stream object we use the function open() void open ( filename, mode); filename is a string of characters representing the name of the file to be opened and mode is a combination of the following flags: ios::in Open file for reading ios::out Open file for writing ios::ate Initial position: end of file ios::app Every output is appended at the end of file ios::trunc If the file already existed it is erased ios::binary Binary mode ofstream file; OR file.open (“file1.abc", ios::out | ios::app | ios::binary); ofstream file (“file1.abc", ios::out | ios::app | ios::binary); TCP1231 Computer Programming I 31
  • 32. More processes To check if the file has been correctly opened we use is_open() that returns a bool type value indicating True in case that indeed the object has been correctly associated with an open file or False otherwise After we finish using the file we must close it, to do that the function close() is used. After we call close(), the stream object can be used to open another file, and the file is available again to be opened by other processes Files This for test ! “Hi and Bye” îyÑå▌┘┬µα╣ ÜÑå«ìæ Text Files Binary Files TCP1231 Computer Programming I 32
  • 33. Closing A File • After using a file, it should be closed – This disconnects the stream from the file – Close files to reduce the chance of a file being corrupted if the program terminates abnormally • It is important to close an output file if your program later needs to read input from the output file • The system will automatically close files if you forget as long as your program ends normally TCP1231 Computer Programming I 33
  • 34. Example TCP1231 Computer Programming I 34
  • 35. Text Files We use the same members of classes that we used in communication with the console (cin and cout). As in the following example, where we use the overloaded insertion operator << #include <fstream> #include <iostream> using namespace std; #include <fstream> using namespace std; int main () { // writing to a text file int main () { // reading a text file ofstream myfile ("file1.txt“, ios::out); char buffer; if (myfile.is_open()) ifstream myfile ("file1.txt“, ios::in); { if (! myfile.is_open()) myfile << “Message from Belal.n"; { cout << "Error"; exit (1); } myfile << “Just Hi and Bye."; myfile.put(‘n’); while (! myfile.eof() ) { myfile.close(); myfile.get (buffer); } cout << buffer; } return 0; return 0; } } eof() TCP1231true if a file opened for reading has reached the end Returns Computer Programming I 35
  • 36. Text Files Read from a file “in.dat” then Write to a file “out.dat” #include <fstream> #include <iostream> using namespace std; int main() { char ch; ifstream infile("IN.DAT"); ofstream outfile("OUT.DAT"); while (infile) { infile.get(ch); outfile.put(ch); } infile.close(); } TCP1231 Computer Programming I 36
  • 37. The End of The File • Input files used by a program may vary in length – Programs may not be able to assume the number of items in the file • A way to know the end of the file is reached: – The boolean expression (in_stream >> next) • Reads a value from in_stream and stores it in next • True if a value can be read and stored in next • False if there is not a value to be read TCP1231 Computer Programming I 37
  • 38. End of The File - Example • To calculate the average of the numbers in a file – double next, sum = 0; int count = 0; while(in_stream >> next) { sum = sum + next; count++; } double average = sum / count; TCP1231 Computer Programming I 38
  • 39. Binary Files When we introduced C++ I/O, we said that input and output streams converted between the programs internal representation for data objects and characters (such as from the internal representation for the number 15 to the characters ‘1’ and ‘5’ and vice versa) Reason for doing this: To translate between the internal binary representation and a format that is easier to understand for humans. Thus, C++ allows us to perform binary file I/O, in which we store and retrieve the original binary representation for data objects TCP1231 Computer Programming I 39
  • 40. Binary Files The advantages of binary file are:  No need to convert between the internal representation and a character-based representation  Reduces the associated time to store/retrieve data  Possible conversion and round-off errors are avoided  Storing data objects in binary format usually takes less space (though this depends on the nature of the data) Disadvantages:  The file is not easily readable by humans  Portability becomes an issue, as different operating systems (and even different compilers) may use different internal representations TCP1231 Computer Programming I 40
  • 41. Creating Binary Files To open a file with a stream object we use the function open() void open ( filename, mode | ios::binary); Creating a stream that will handle binary I/O is as simple as setting a flag Create a binary file output stream: ofstream fout (“myFile.txt”, ios::out |ios::trunc | ios::binary); Create a binary file input stream: ifstream fin (“myFile2.txt”, ios::in | ios::binary); TCP1231 Computer Programming I 41
  • 42. Binary Files (read and write) Two functions are used : READ & WRITE write() –Lets us write a specified number of characters to an output stream –does a straight byte-by-byte copy fout.write(reinterpret_cast<char *>(&obj), sizeof obj); read ( ) –Lets us read a specified number of characters to an output stream –does a straight byte-by-byte read fin.read(reinterpret_cast<char *>(&obj), sizeof obj); TCP1231 Computer Programming I 42
  • 43. Example #include <iostream> ofstream output; #include <fstream> output.open("indata.dat", ios::out|ios::binary); #include <cstring> output.write(reinterpret_cast<char *>(&people), using namespace std; sizeof(person) ); output.close(); typedef struct { char gender; person newperson; int age; ifstream input; string name; input.open("indata.dat", ios::in|ios::binary); } person; input.read(reinterpret_cast<char *> (&newperson), sizeof(person) ); int main(void) cout << "n Name is ==> " << newperson.name; { cout << "n Gender is ==> " << newperson.gender; person people; cout << "n Age is ==> " << newperson.age; people.name= "Ali"; input.close(); people.age= 22; people.gender= 'm'; return 0; } TCP1231 Computer Programming I 43
  • 44. File Seek The C++ I/O system supports four functions for seeking seekg() ifstream Moves get file pointer to a specific location seekp() ofstream Moves put file pointer to a specific location tellg() ifstream Returns the current position of the get pointer tellp() ofstream Returns the current position of the put pointer moves the file pointer to the 20th byte in Origin value Seek From … the file, infile. After this, if a read ios::beg seek from beginning of file operation is initiated, the reading starts ios::cur seek from current location from the 21st item within the file. ios::end seek from end of file moves the file pointer to the infile.seekg(20, ios::beg); or infile.seekg(20); 20th byte in the file outfile. After this, if write operation is outfile.seekp(20, ios::beg); or outfile.seekp(20); initiated, the writing starts from the 21st item within the file. TCP1231 Computer Programming I 44
  • 45. Seek Seek call Action performed outfile.seekg(0, ios::beg) Go to the beginning of the file outfile.seekg(0, ios::cur) Stay at the current file outfile.seekg(0, ios::end) Go to the end of the file outfile.seekg(n, ios::beg) Move to (n+1) byte location in the file outfile.seekg(n, ios::cur) Move forward by n bytes from current position outfile.seekg(-n, ios::cur) Move backward by n bytes from current position outfile.seekg(-n, ios::end) Move forward by n bytes from the end infile.seekg(n, ios::beg) Move write pointer to (n+1) byte location infile.seekg(-n, ios::cur) Move write pointer backward by n bytes TCP1231 Computer Programming I 45
  • 46. Examples,,, seekp, tellp ofstream fout(“myFile.txt”); if (fout.is_open()) { fout << “Hello, this is a file.” << endl; fout.seekp(15); fout << “not a file“; ofstream fout(“myFile.txt”); if (fout.is_open() ) { fout << “Hello,this is a file.” << endl; fout.seekp(fout.tellp()– static_cast<streampos>(8)); fout << “not a file“; ofstream fout(“myFile.txt”); if (fout.is_open()) { fout << “Hello, this is a file.” << endl; fout.seekp(-8, ios_base::cur); fout << “not a file“; TCP1231 Computer Programming I 46
  • 47. Examples,,, seekg, tellg ifstream fin(“myFile.txt”); if (fin.is_open()) { char c; fin.seekg(5, ios_base::cur); fin >> c; … } ifstream fin(“myFile.txt”); if (fin.is_open() ) { char c; fin.seekg(fin.tellg()–static_cast<streampos>(5) ); fin >> c; … } TCP1231 Computer Programming I 47
  • 48. The End TCP1231 Computer Programming I 48