Pages

Sunday, August 21, 2011

Process of File Handling

Process Of File Handling

  1. Select Link/Stream Type : The first step in file handling is to determine what we want to "do" with the file - read,write or both. Once the "need" is known, we can select the appropriate "stream" to the desired operation. The following classes are can be used for various function.
    • Reading a file (From the file to memory) : Reading refers to the process of reading or traversing the data of a file either fully or partially. If we are searching the data in the file it will also be referred to as "reading". To read a file in C++, we must use the "ifstream" class.  It can be used in two modes, here is the syntax for both of them
      a) Using Constructor : ifstream in("filename")
      b) Using Open() Function :
      ifstream in;
      in.open("filename", ios::in);

      Note that with open(), a file mode(ios::in) is used. ios::in is the default mode for ifstream and can be removed also. For a complete list of file modes Click here
    • Writing a file (From the memory to file) : Writing refers to the process of storing data in a file. The data can be either static or can be asked from the user.The "ofstream" class is used to write data in the file. Like ifstream it too can be used in two modes,
      a) Using Constructor : ofstream in("filename")
      b) Using Open() Function :
      ofstream out;
      out.open("filename", out.write);
      Again the "out.write" mode is the default mode for "out".
    • Writing and Reading (From the memory to file and file to memory) : If we want to write and read the data from a file at the same time, then instead of first opening the file in "ofstream" and then in "ifstream", we can use the "fstream" class that can perform both "writing and reading" operations. This will save the time and memory that will be required where file are closed and reopened.
      fstream file;
      file.open("filename",ios::in | ios::out );
      Since fstream can perform both reading and writing tasks, it is compulsory to specify the modes to let the compiler know what kind of operation we want to perform.
  2.  Process the file as required :  Once the file is opened, the next step is the process the file as required. For example, if the program is for writing the data, then using the appropriate functions the data should be written or if the reading of the file is required then proper functions should be used to read the file.
  3. Close the file : After processing the file, it is better to close it so that the memory resources allocated to it are released. A file once closed, can be reopened anytime if required. To close a file the close() function is used.
    in.close();
    out.close();


0 comments:

Post a Comment