Topic :Sequential Files: Opening Files | Closing files | Writing to File | Reading from File | Deleting File



Sequential Files:

A Sequential file has to be Accessed in the same order the file was written. Let's take an example of Cassette Tapes: We play music in the same order it was recorded. we can Quickly fast-forward or rewind over songs we don't want to listen to, but the order of the songs dictates what we do to play the song we want. But it is difficult, and sometimes impossible, to insert data in the middle of two other songs on a tape. The Only way to truly add or delete records from the middle of a Sequential file is to create a completely New file that combines both old and new records. With Sequential files, we can do following steps in C++ programming language:




image: Sequential File Handling

Opening & Closing File:

In C++, The Process of Opening/Closing or Manipulating Files requires a lot of Language background to prepare us for the Complexity of the Operations. However, The C++ Library Provides a simple way to manipulate files, so in just few easy steps we can Open or close any file, or Manipulating, it's all easy in C++ using C++ Iostream and fstream library:



Make sure you Include <iostream> and <fstream> header file in your program to do file Operation:


A File must be opened before we can read from it or write to it. We can use fstream object to open a file for writing or reading purpose. but if we use ifstream object, we can open a file for reading purpose only. and if use ofstream object, we can open a file for writing purpose only. Following is the Standard Syntax to Open File.



fstream myFile;
myFile.open(" filename.txt", ios::openMode);


Where Myfile is an object of type fstream, because fstream is an class so we need to create an object to use member function of fstream class. Next, using myFile object we call an member function open() , this Function Need two arguments to processing. The first is FileName (Which could be any that you want to called your file) and the second is File Opening Mode. A File can be opened in Different modes to perform reading and Writing Operations. C++ supports the following file open modes:



File Mode ParameterMeaning Explanation
ios::inReadOpen the file for Reading Purpose Only: if the file don't exist, it will generate an error.
ios::outWriteOpen the file for Writing Purpose Only: if the file already exist, then this mode will open the file and format it. and if there is no file exist, then this mode will create New file.
ios::appAppendingOpen the file for Appending data to end of the file. Using this mode we can Open an already existing file and over write it. but in this mode we can write only at the end of the file.
ios::ateAppendingIt's same like ios::app mode. Open file using this mode will take us to end of the file. but we can write any where in file.
ios::binaryBinaryOpen file in Binary mode:
ios::truncTruncate/Discard When we will open the file using this Mode. this mode will delete all data if the file already existing.
ios::nocreateDon't Create This Mode can just open an already existing file. if the file not exist, it will show an error.
ios::noreplaceDon't ReplaceThis mode is used to open new file. if the file is already exist, it will show an error.


The default value for fstream mode parameter is in | out. it means that file is opened for reading and writing when we use fstream class. When we use ofstream class, default value for mode is out and the default valur for ifstream class is in.


We can use More than one file mode using bit wise operator " | "


Closing File:

A File must be close after completion of all operation related to file. When C++ program terminates, it automatically flushes all the streams, release all the allocated memory and close all the opened files. But it is always a good practice that a programmer should close all the opened files before program termination. Following is the standard syntax for Close the file:


file_object.close();


Close() is an member function of fstream, ifstream and ofstream objects. Now let's take an example, where we can open an New file and then close it:



/* Opening & closing files Example: InfoBrother:*/
 
#include<iostream>//Required for input & output: 
#include<fstream>//Required for File function:
using namespace std;
 
int main()
{
    /*Create New file: in just Write Mode:*/
   fstream myFile;
   cout<<"WRITING PURPOSE:"<<endl;
   myFile.open("InfoBrother.txt",ios::out); //open file in writing mode:
 
   if(!myFile) //error checker: if file did'nt open:
   {
      cout<<"Error while Opening File: "<<endl;
   }
   else cout<<"New File Open Successfully for Writing Purpose:"<<endl;
 
   myFile.close(); //close the file:
   if(myFile.is_open()==NULL) //error checker, if file still open:
   {
      cout<<"File has been Closed" <<endl;
   }
   else cout<<" File still Open: "<<endl;
 
 
   /*Open Existing File for Reading and Appending Purpose:*/ 
   cout<<"\n\nREADING & APPENDING PURPOSE: "<<endl;
   myFile.open("InfoBrother.txt", ios::in | ios::app); //file Opening:
 
   if(!myFile)
   {
      cout<<"Error While Opening File: "<<endl;
   }
   else cout<<" Existing File Open Successfully for Reading & Appending Purpose: "<<endl;
 
   //Let's dont close the file and check the error:
   if(myFile.is_open()==NULL) 
    {
        cout<<" File has been closed: "<<endl;
    }
    else cout<<"File still Open: "<<endl;
 
   return 0;
}


In above Example, I just create an object myFile of Class fstream and using that object i just open and close the file. (i.e. InfoBrother.txt ). it's really simple and easy to play with fstream class. did you Notice some Error checker in my program? its really good programming practice to include error checker in our program. the error checker code help us to reduce error in our program. so always try to include error checker where ever its possible.


Open(): It's used to open the file, it take two argument. the first is the fileName and other is Opening Mode:

close(): It's used to close the Opened file. and it don't need any argument:

is_open(): It's used to check the file is Open. if the file is open it's return true, else return false:

In above example - i used some member function of class fstream. Open() , close() and is_open() These all are the member function of fstream class.

if you copy the above example and compile it yourself, then you can check the folder where you are compiling your C++ Programs. you will find "InfoBrother.txt" file over there.



Writing to File & Reading From file:

Now we know that how to open or close a file. it's time to learn that how to write files in C++ Programming Language. While doing C++ Programming, we write information to a file from our program using streams insertion Operator << just as we use that operator to output information to the screen. The only difference is that we use an ofstream or fstream object instead of the cout object. in order to write to files, we have following methods:



Some Important Function To read and Write Data:
MethodSyntaxExplanationExample
get()get(ch, size)This Function Get input character by character including spaces, tabs, and newline upto size and assign to the variable ch. this function is useful for limited number of characters sent to a specific variable. this function Needs two arguments, 1st is char array, and other is size of array. this function can take an optional parameter which is a delimiter ('\n' by default)
getline()getline(Array_name, size)getline() function is similar to get() function, but it read whole line of text that end with newline character. this function need two parameter, first is char array, and other is array size. this function can take an optional parameter which is a delimiter ('\n' by default).
Insertion Operator (<<)stream <<Same like cin, we can use fstream or ofstream object to get data form user with insertion operator.


Reading From Files:

Once the data is in a file, we must be able to read that data. we must open the file in a read access mode. There are several ways to read data. We can read character data one character at a time or one string at a time. The choice depends on the format of the data. Files we open for read access (using ios::in) must exist already, or C++ gives an error. we can't read a file that does not exist. open() returns zero if the file does not exist when we open it for read access.

Let's create an simple program which can open given file and read it. In this case we need to open file using ios::in mode. so the file, we need to read must be already there.. it can read only existing file.



It's better if you can place your file in the same folder where you compiling your program. otherwise, you need to give the complete path to open a file.



/* Reading from Sequential files: InfoBrother:*/
 
#include<iostream>//Required for input & output: 
#include<fstream>//Required for File function:
using namespace std;
 
int main()
{
   ifstream myFile; //object of type ifstream:
   char fileName[20]; //will use to store fileName from user:
   char ch; //will use to read all data from file:
 
 
   cout<<" Enter the Name of the file you want to read: "<<endl;
   cin>>fileName; 
 
   myFile.open(fileName, ios::in); //open file for reading purpose:
 
   if(!myFile) //error checker: if file not exist:
   {
       cout<<"Error While Opening File: "<<endl;
   }
 
 
   else //if file exists and open successfully:
   {
       cout<<"File Open Successfully: here is the result: "<<endl;
       while(!myFile.eof()) //read till end-of-file:
       {
            myFile.get(ch); //read data from file:
            cout<<ch; //display data on screen:
       }
   } 
 
   myFile.close(); //close the file:
 
   return 0;
}


It's the same file that I write using Insertion operator in Above Example: Because Newline characters are in the file at the end of each name, the names appear on-screen, one per line. if we attempt to read a file that does not exist, then our error checker will show an error.



In above Example, We use a Function eof() mean end-of-file.
eof(): This function is used to indicate that the End-of-file has been reached. This is the special function that returns true if there are no more data to be read from an input file stream, and return False otherwise:



Let's create another Program, A Copy Program . This Program reads one file and copies it to another. This Program will open two files, one for reading and other for writing.



/*Copying File Program: InfoBrother*/
 
#include<fstream>//required for file operation:
#include<iostream>//required for input/output:
using namespace std;
 
main()
{
    char File1[20],File2[20],ch; //variable to store file-Names
    ifstream in_file; //Object for Input file
    ofstream out_file; //Object for Output file
 
    cout<<" Enter The Name Of File To be Copy: \n";
    cout<<" File Name:";
    cin>>File1;
    cout<<" Enter The Name of File Where To copy: \n";
    cout<<" File Name:";
    cin>>File2;
 
    in_file.open(File1,ios::in); //file Open for reading purpose: (copy)
    if(!in_file) //Error Checker: if file not open:
    {
        cout<<"An Error Occur While Opening File: \n";
    }
 
    out_file.open(File2,ios::app); //file Open for writing purpose: (paste)
    if(!out_file) //Error Checker: if file not open:
    {
        cout<<"An Error Occur While Opening Filef: \n";
    }
 
    while (in_file.get(ch)) //read data from file: (copy data)
    {
       out_file.put(ch); //paste it here:
    } 
 
    in_file.close(); //closing files:
    out_file.close();
    cout<<" \n\n Copy Successful...!! : \n";
 
    return 0;
}


In Above Example, we just copy from one file and paste it into another file. the program read data character by character, and paste it into new file character by character. copy this example and paste it into your compiler. read from one already existing file and paste it to another file. then open your folder where you compile your program to make sure that there is the New text file with the same content of first file.



Deleting File:

In Sequential File we can delete complete file using remove() Member function. This function need one argument which is the name of the file: the basic syntax for deleting file is:


remove("fileName");


The default access mode for file access is a text mode, but we can change this default access mode to any extension. But it's better if we can use Binary Modes.













I Tried my Best to Provide you complete Information regarding this topic in very easy and conceptual way. but still if you have any Problem to understand this topic, or do you have any Questions, Feel Free to Ask Question. i'll do my best to Provide you what you need.

Sardar Omar.
InfoBrother





WRITE FOR INFOBROTHER

Advertising






Advertisement