Data Structures

Document Sample
Data Structures Powered By Docstoc
					                        Andreas Savva




Programming Principles II

      Lecture Notes 7
           Files
                            Files
   A file is a group of organized data stored in secondary
    storage.
   Every file has a filename – the name by which the operating
    system refers to the contents of the file.


                            Letter.txt
                  Dear Ann
                  I am now living in Cyprus where I
                  got married and bought a house.
                  This is a great place to be. The
                  weather is perfect and life is . . .




                                                           2
                    Type of Files
   The operating system usually distinguishes files in different
    categories:
       Text file (contains ASCII characters)
       Executable (Contains code of a program)
       Binary file (contains arbitrary data)


   Application programs usually store data in binary files in a
    format understood only by the specific application program
    e.g.
       MS Word documents (.doc)
       MS Excel files (.xls)
       GIF image files (.gif)



                                                              3
             File Handle in C++
   In order to be able to handle a file we need to:
       include the library fstream.
       declare an object to represent a file which will permit reading,
        writing, etc.
   C++ provides the following classes to perform input and
    output from/to files:
       ofstream: stream class to write in files
       ifstream: Stream class to read from files
       fstream: Stream class to read and write from/to files
                       #include <iostream>
                       #include <fstream>
                       using namespace std;
                       int main() {
                          fstream myFile;
                          . . .
                          return 0;
                       }                                                   4
                   Opening a File
   To open a file we must:
       determine the file name (e.g. data.txt)
       create a new file handle (e.g. myFile)
       use the handle to open the file myFile.open(filename, mode)
   To open an existing file to read from, the mode must be
    ios::in.

             #include <iostream>
             #include <fstream>
             using namespace std;
             int main() {
               fstream myFile;
               myFile.open(”data.txt”,ios::in);
               . . .
               return 0;
             }
                                                                      5
         Using fstream Objects
   In using both ifstream and ofstream objects the mode,
    input or output, is implied by the object. Thus,
       ifstream objects can only be used for input
       ofstream objects can only be used for output
       fstream objects can be used for input or output but require an
        explicit mode designation.
             #include <iostream>
             #include <fstream>
             using namespace std;
             int main() {
                ifstream inFile;
                ofstream outFile;
                fstream addFile;
                inFile.open(”in.txt”,ios::in);
                outFile.open(”out.txt”,ios::out);
                addFile.open(”new.txt”,ios::app);
               . . .
                return 0;
             }                                                      6
                     Opening a File Mode
   Mode is an optional parameter with a combination of the following flags:

       Mode               Description
       ios::in            Open a text file in input mode
       ios::out           Open a text file in output mode
       ios::app           Open a text file in append mode
       ios::ate           Go to the end of the open file
       ios::binary        Open a binary file in input mode (default is text file)
       ios::trunc         Delete file contents if file exists



   All these flags can be combined using the bitwise operator OR (|). For example,
    the following will open a the file example.bin in binary mode to add data:

       fstream myFile;
       myFile.open(”example.bin”, ios::out | ios::app | ios::bin);


                                                                                    7
                 Default Modes
   Each one of the open() member functions of the classes ofstream,
    ifstream and fstream has a default mode that is used if the file is
    opened without a second argument, i.e.

                  ofstream myFile;
                  myFile.open(”data.txt”);


                Class      Default mode parameter
                ofstream   ios::out
                ifstream   ios::in
                fstream    ios::in | ios::out


   The three classes have a constructor that takes the same parameters
    as open() and automatically calls it.

           ofstream myFile(”data.txt”, ios::out);
                                                                   8
                  Opening a File
   File streams opened in binary mode perform input and output
    operations independently of any format considerations.
   Non-binary files are known as text files, and some translations may
    occur due to formatting of some special characters (like newline and
    carriage return characters).
   The method is_open() with no arguments (returns a bool value) can
    be called to check whether or not a file stream has successfully
    opened a file.

              ofstream myFile(”data.txt”);
              if (myFile.is_open())
              {
                 // ok, proceed with output
              }
              else cout << ”Unable to open file”;

                                                                    9
        Reading from a Text-File
   Data output and input operations on text-files are performed in the
    same way as with cout and cin.
                                                      data.txt
#include <iostream>
#include <fstream>                              3458 Jurassic Park
using namespace std;
int main() {
  ifstream inFile(”data.txt”);                     458Jurassic3
    if (inFile.is_open()) {
      char ch;
                       Ignores spaces
      int k;             and control
      char s[50];        characters
                                                      data.txt
      inFile >> ch;                               34A58B Jurassic Park
      inFile >> k >> s;
      cout << k << s << ch;
    }                                              4A58B3
    return 0;
}
                                                                         10
               Reading Methods
   There exist a variety of methods for reading streams
    (files).
       Read a single character, including spaces and control characters:
                        ch = myFile.get();
       Read a line of text or up to 20 characters into array s[] :
                      myFile.getline(s,20);
       Read a line of text or up to 20 characters or until character ’A’
        occurred into array s[] :
                myFile.getline(s,20,’A’);
   cin is also a stream object; we can use the same
    operations:
                       ch = cin.get();
                     cin.getline(s,20);
                  cin.getline(s,20,’A’);                                    11
         Exceptions and Errors
   With file operations there may be a variety of problems,
    i.e.
       File not found during opening.
       File cannot be opened (already opened exclusively by other
        program).
       End of file reached.
       Disk full during writing.

   Detecting when a problem occurred:
                             !myFile
                          myFile.fail()

           myFile.open("data.txt",ios::in);
           if (!myFile) // an error has occurred
              cout << ”Could not open file”;
           . . .
                                                                     12
          Checking State Flags
   A number of bool member functions exist to check for specific states
    of a stream:

Method      Description
bad()       Returns true if a reading or writing operation fails. For example, if
            there is an attempt to write in a file that was open for input, or if
            there is no available memory on the device that there is an
            attempt to write in a file.
fail()      Returns true in the same cases as bad(), but also in the case that
            a format error happens. For example if a character is extracted
            while an integer is expected.
eof()       Returns true if a file opened for input has reached the end.
good()      It is the most generic state flag – it returns false in the same cases
            in which calling any of the previous functions would return true.



                                                                               13
                 Closing a File
   After completing the use of the file, it should be closed so
    that it resources become available again.
   Closing a file:
                    myFile.close();
   Once closing the file, the file becomes available to be
    opened by other processes and the stream object can be
    used to open another file.
   In case that an object is destructed before is closed the
    destructor calls the member function close().



                                                             14
         Reaching the End of File
   The method eof() determines if the end of the file is reached.

       // the following program reads lines and displays
       // them on the screen until the end of the file.
       #include <iostream>
       #include <fstream>
       using namespace std;
       int main() {
           fstream myFile;
           char str[256];
           myFile.open("data.txt", ios::in);
           if (myFile.is_open()) {
               while(!myFile.eof()) {
                   myFile.getline(str,256); // get a line
                   cout << str << endl;         // display line
               }
               myFile.close();
           }
           else cout << ”Unable to open file”;
           return 0;
       }                                                             15
            Using method good()
   The method good() can be used instead of the method eof() .

       // the following program reads lines and displays
       // them on the screen until the end of the file.
       #include <iostream>
       #include <fstream>
       using namespace std;
       int main() {
           fstream myFile;
           char str[256];
           myFile.open("data.txt", ios::in);
           if (myFile.is_open()) {
               while(myFile.good()) {
                   myFile.getline(str,256); // get a line
                   cout << str << endl;         // display line
               }
               myFile.close();
           }
           else cout << ”Unable to open file”;
           return 0;
       }                                                          16
                Writing to a File
   Similar to opening for reading, but use ios::out
    when opening:
        myFile.open("data.txt", ios::out);
   Consequences to file:
       If the file does not exist, it is created.
       If it exists its data is overwritten.


   Writing to a file:
     myFile << ”Hello” << 12 << ’C’ << endl;

                                                       17
Copying a File to Another File
#include <iostream>
#include <fstream>
using namespace std;
int main() {
   fstream fin, fout;
   char str[256];
    fin.open("data.txt", ios::in);
    if (fin.is_open()) {
       fout.open("newdata.txt", ios::out);
      while(!fin.eof()) {
         fin.getline(str, 256); // get a line
         fout << str << endl;   // put a line
      }
    }
    fin.close();
    fout.close();
    return 0;
                                                18
}
          Appending to a File

   Data can be appended at the end of the file by
    using ios::app when opening.
   Existing data will not be overwritten.

      myFile.open("data.txt", ios::app);




                                                     19
                 Constant EOF
#include <iostream>
#include <fstream>
using namespace std;                               data.txt
int main() {                                My name is George and
   fstream fin, fout;                       I live in London.
   char ch;
    fin.open("data.txt", ios::in);
    if (!fin) cout << "File not found";
    else {
       fout.open("newdata.txt", ios::out);
      ch = fin.get();        Character denoting
      while(ch != EOF)         the end of file
      {
         if (ch >= ’A’ && ch <= ’Z’) fout << ’?’;
         else fout << ch;
         ch = fin.get();
      }                                         newdata.txt
      fin.close();                         ?y name is ?eorge and
      fout.close();
    }                                       ? live in ?ondon.
    return 0;
}                                                               20
    Stream Pointers: get and put
   All i/o stream objects have, at least, one internal stream
    pointer:
       ifstreams like istream, has a pointer known as get pointer that
        points to the element to be read in the next input operation.
       ofstreams like ostream, has a pointer known as put pointer that
        points to the location where the next element will be written.
   These internal stream pointers that point to the reading
    or writing locations within a stream can be manipulated
    using the following member functions:
       tellg() and tellp() – These two functions return a value of the
        member type pos_type, which is an integer data type,
        representing the current position of the respective pointer.
       seekg(position) and seekp(position) – These functions change
        the position of the respective pointers. The pointer is changed to
        the absolute position (counting from the beginning of the file).
        Parameter position is of member type pos_type (integer).
                                                                       21
                Stream Pointers
                                                   data.txt
#include <iostream>
#include <fstream>                           My name is George and
using namespace std;                         I live in London.

int main() {
   ifstream fin(”data.txt”);
   if (fin.fail()) cout << "File not found";
   else {
      char ch;                               My nameand
      while(ch = fin.get(), ch != EOF)       I live in London
      {
         cout << ch;
         if (fin.tellg()==fstream::pos_type(7))
             fin.seekg(18);
      }
      fin.close();
   }
   return 0;
}


                                                                22
           Overloaded Methods for
         changing the Stream Pointers
   There is an overloaded function for both member functions seekg and
    seekp:
                   seekg( offset, direction )
                   seekp( offset, direction )

   The position of the get or put pointer is set to an offset value relative
    to some specific point determined by the parameter direction.
    Parameter offset is of the member type off_type, which is an integer
    type and direction is of type seekdir which is an enumerated type that
    determines the point from where offset is counted from, and that can
    take any of the following values:
    direction   Description
    ios::beg    offset counted from the beginning of the stream
    ios::cur    offset counted from the current position of the stream pointer
    ios::end    offset counted from the end of the stream
                                                                            23
           Changing the Stream Pointers
                    Examples

Code                   Description
seekg(0, ios::end);    Pointer get will be set at the end of the stream
seekg(-2 ,ios::end);   Pointer get will be set two positions before the end of the stream
seekg(-1, ios::cur);   Pointer get will be set one position before its current position
seekp(2, ios::beg);    Pointer put will be set two position after the beginning of the stream



          Display the size of the file:
          myFile.seekg(0, ios::end);
          long size = myFile.tellg();
          cout << ”Size is ” << size << ” bytes”;



                                                                                            24
                 Unget Character                     data.txt
Display the words starting with ‘a’:       i traveled abroad to
int main() {                               amsterdam and i was
   ifstream fin("data.txt");               very happy to go around
   if (fin.fail()) cout << "File not found";
   else {                                  and see this amazing city
      char ch, s[100];
      ch=fin.get(); fin.unget();
      if (ch == 'a') {
          fin >> s;
          cout <<s<<endl;
      }                                         abroad
      while (ch=fin.get(), ch!=EOF) {           amsterdam
          if (ch == ' ') {                      and
             ch = fin.get();
             if (ch == 'a') {                   around
                fin.seekg(-1,ios::cur);         and
                fin >> s;                       amazing
                cout << s << endl;
             }
          }
      }
      fin.close();                  fin.unget();
   }
   return 0;
}                                                               25
                     Binary Files
   In binary files, to input and output data with the extraction and
    insertion operators (<< and >>) and functions like getline is not
    efficient, since there is no need to format data, and data my not use
    the separation codes used by text-files to separate elements (like
    spaces, newlines, etc.)
   For binary files, file streams include two member functions for input
    and output.
     read( char* memory_block, int size ) – ifstream, fstream
     write( char* memory_block, int size ) – ofstream, fstream



   where memory_block is the address of an array of bytes and size is an
    integer.



                                                                    26
    Writing Structures to Binary Files
              class human {
              public:
                 human(){}
                 human(char s[], int x) {
                    strcpy(name,s);
                    age = x;
                 }
              private:
                 char name[50];
                 int age;
              };
void write_to_file()
{
   char name[50];
   int age;
   cout << "Enter name and age: ";
   cin >> name >> age;
   human person(name,age);

    ofstream myFile("data.bin", ios::app | ios::binary);
    myFile.write((char*)&person, sizeof(human));
    myFile.close();
}
                                                           27
  Reading Structures from Binary Files
void read_from_file(human people[], unsigned long &n) {
   ifstream myFile("data.bin", ios::binary);
   if (myFile.fail()) cout << "File not found";
   else {
      myFile.seekg(0,ios::end);                  Reading records
      n = myFile.tellg()/sizeof(human);            one-by-one
      myFile.seekg(0);
      for (unsigned long i=0; i<n; i++)
         myFile.read((char*)&people[i], sizeof(human));
      myFile.close();
   }
}
void read_from_file(human people[], unsigned long &n) {
   ifstream myFile("data.bin", ios::binary);
   if (myFile.fail()) cout << "File not found";
   else {                                        Reading records
      myFile.seekg(0,ios::end);                    all at once
      n = myFile.tellg()/sizeof(human);
      myFile.seekg(0);
      myFile.read((char*)people, sizeof(human)*n);
      myFile.close();
   }
}                                                            28
          Buffers and Synchronization
   File streams are associated to an internal buffer of type streambuf. This buffer is
    a memory block that acts as an intermediary between the stream and the
    physical file. For example, with an ofstream, each time the member function put
    (which writes a single character) is called, the character is not written directly to
    the physical file with which the stream is associated. Instead, the character is
    inserted in the stream’s intermediate buffer.
   When the buffer is flushed, all the data contained in it is written to the physical
    medium (if it is an output stream) or freed (if it is an input stream). This process
    is called synchronization and takes place under the following circumstances:
        When the file is closed: before closing a file all buffers that have not yet been
         flushed are synchronized and all pending data is written or read to the physical
         medium.
        When the buffer is full: Buffers have a certain size. When the buffer is full it
         automatically synchronized.
        Explicitly, with manipulators: When certain manipulators are used on streams, an
         explicit synchronization takes place. These manipulators are: flush and endl.
        Explicitly, with member function sync(): calling stream’s member function
         sync(), which takes no parameters, causes an immediate synchronization. This
         function returns an int value equal to -1 if the stream has no associated buffer or in
         the case failure. Otherwise (if successful) it returns 0.
                                                                                         29

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:2
posted:2/19/2012
language:
pages:29