Topic :Random Access Files: Seekg() Write() Read() Remove() Rename()



Seekg()

Seekg() function allow us to move the Input pointer to specified location for reading purpose within the file. The basic syntax for seekg() function is:


fileObject.seekg(long_num,  origin);

  • In Above Syntax:

    » Fileobject is the Pointer to the file that we want to access.
    » Long_num is the number of bytes in the file we want to skip.
    » Origin is the value that tells compiler, where to begin the skipping of Bytes specified by long-num.

    Origin can be any of the three values, shown below.




Go to Start:

No matter how far into a file we have read, by using this syntax, the file-pointer will back to the beginning of the file.

The basic syntax to use this origin with seekg() function is-


fileObject.seekg(0,   ios::beg);

Let's have a simple example to understand how we can use this syntax in our C++ program.


/*Seekg(long_num, ios::beg) Example: InfoBrother*/
 
#include<fstream>//required for file operation:
#include<iostream>//required for input/output:
using namespace std;
 
main()
{
	ofstream myFile; //Object for Writing:
	ifstream file;   //Object for reading:
	char ch[30];     //Arguments: name & size of array.
	char text;       //character variable to read data from file:
 
	cout<<"Enter some Text here: "<<endl;
	cin.getline(ch,30);  //Getline function.
 
       //opening file for Writing:
	myFile.open("InfoBrother.txt", ios::out); 
	if(myFile) //Error Checker: 
	{
    	   myFile<<ch;
    	   cout<<"Data store Successfully: \n\n"<<endl;
	}
	else cout<<" Error while opening file: "<<endl;
	myFile.close(); //file close:
 
	//opening file for reading:
	file.open("InfoBrother.txt", ios::in); 
	if(file) //Error Checker:
	{
    	   file.seekg(7, ios::beg); //skip first 7 bytes from beginning:
    	   cout<<" The output( after skipping first 7 bytes) is: ";
 
    	   while(!file.eof()) //read data from file till end of file:
    	   {
        	file.get(text); //read data:
        	cout<<text;     //display data:
    	   }
	}
	else cout<<" Error while Opening File: "<<endl;
	file.close(); //file close:
 
	return 0;
}


Stay at Current position:

Stay at current position, where you are. Using this syntax, the file-pointer will show its current position.

The basic syntax to use this origin with seekg() function is-


fileObject.seekg(0,   ios::cur);

Let's have a simple example to understand how we can use this syntax in our C++ program.


/*Seekg(long_num, ios::cur) Example: InfoBrother*/
 
#include<fstream>//required for file operation:
#include<iostream>//required for input/output:
using namespace std;
 
main()
{
	ofstream myFile; //Object for Writing:
	ifstream file;   //Object for reading:
	char ch[30];     //Arguments, Name & size of Array.
	char text;       //character variable to read data from file:
 
	cout<<"Enter some Text here: "<<endl;
	cin.getline(ch,30);  //getline function
 
	//opening file for Writing:
	myFile.open("InfoBrother.txt", ios::out); 
	if(myFile) //Error Checker: 
	{
    	   myFile<<ch;
    	   cout<<"Data store Successfully: \n\n"<<endl;
	}
	else cout<<" Error while opening file: "<<endl;
	myFile.close(); //file close:
 
        //opening file for reading:
	file.open("InfoBrother.txt", ios::in); 
	if(file) //Error Checker:
	{
    	   file.seekg(7, ios::beg); //skip first 7 bytes from beginning:
    	   file.seekg(-2, ios::cur); //then move back 2 bytes from current position:
 
    	   cout<<" The output (after skipping first 7 bytes and then move 2 bytes back) is: ";
    	   while(!file.eof()) //read data from file till end of file:
    	   {
        	file.get(text); //read data:
        	cout<<text; //display data:
    	   }
 
	}
	else cout<<" Error while Opening File: "<<endl;
	file.close(); //file close:
 
	return 0;
}


Go to End of the File:

Go to End of the file where ever you are. Using this syntax, the file-pointer will point to end of the file.

The basic syntax to use this origin with seekg() function is-


fileObject.seekg(0,   ios::end);

Let's have a simple example to understand how we can use this syntax in our C++ program.


/*Seekg(long_num, ios::end) Example: InfoBrother*/
 
#include<fstream>//required for file operation:
#include<iostream>//required for input/output:
using namespace std;
 
main()
{
	ofstream myFile;//Object for Writing:
	ifstream file; //Object for reading:
	char ch[30];   //Arguments - Name & size of Array.
	char text;     //character variable to read data from file:
 
	cout<<"Enter some Text here: "<<endl;
	cin.getline(ch,30);
 
	//opening file for Writing:
	myFile.open("InfoBrother.txt", ios::out); 
	if(myFile) //Error Checker: 
	{
    	   myFile<<ch;
    	   cout<<"Data store Successfully: \n"<<endl;
	}
	else cout<<" Error while opening file: "<<endl;
	myFile.close(); //file close:
 
        //opening file for reading:
	file.open("InfoBrother.txt", ios::in);
	if(file) //Error Checker:
	{
	   //from end of file, move pointer 11 bytes backword:
    	   file.seekg(-11, ios::end); 
    	   cout<<"\n The last 11 bytes are: ";
 
	   while(!file.eof()) //read data till end of the file:
	   {
    		file.get(text); //read:
    		cout<<text; //display:
	   }
	}
 
	else cout<<" Error while Opening File: "<<endl;
	file.close(); //file close:
 
	return 0;
}


Write() function:

This function is used with Output-Pointer object to write the Block of data. Write() Function uses the binary version of data instead of the text version. when write() is used, each value is stored in its binary format and each record is created to have a fixed length. The write function takes three arguments, first is Pointer to Character, the second is Address of the object, and last the size of Object.

The basic syntax to use this function is -


write( (char *) &Obj,  sizeof(Obj));

Let's have a simple example to understand the concept of write() function and how we can use it to write the block of data in our C++ program.


void WriteEmployee() //Write Employee data into the file:
{
    fp.open("Employe.txt",ios::out); //open file for writing:
    if(fp) // error chacker
    {
        Emp.getEmp_data(); //funtion calling.
        fp.write((char*)&Emp,sizeof(Emp)); //Write into file:
        cout<<"Record Store Successfully: "<<endl;
    } 
 
    fp.close();        
} 

In above Example, the write() function will take the block of data, and store it in the file.




Read() function:

This function is used with Input-Pointer object to read the block of data. It's same like write() Function, but in sense of reading.


read( (char *) &Obj,  sizeof(Obj));

Let's have a simple example to understand the concept of write() function and how we can use it to write the block of data in our C++ program.


void W_displayEmp() //display data from file:
{
    fp.open("Employe.txt",ios::in); //Open same file for reading:
    if(fp) //error chacker
    {
       while(fp.read((char*)&Emp,sizeof(Emp))) //read data form file:
       {
          Emp.showemp_data(); //function calling
       }
 
       fp.close();
    }
}



Read() & Write() Complete Example:
/*Write() and Read() function Example: InfoBrother*/
 
#include<fstream>//required for file operation:
#include<iostream>//required for input/output:
using namespace std;
 
//we are using this class to get data from user and display:
class Employee 
{
    private: //private Members of class
        char name[30];
        char employe_ID[20];
        char joining_DATE[20];
        char position[20];
        char marital_status[10];
        char age[10];
        char salary[20];
        char comment[80];
 
    public:
     void getEmp_data() //Get employee data:
     {
         cout<<"Welcome To InfoBrother: "<<endl;
         cout<<"======================";
         cout<<"\n\n Employee Name: ";
         cin.getline(name,30);
         cout<<" Employee ID: ";
         cin.getline(employe_ID,20);
     	 cout<<" Joining Date: (DD/MM/YYYY) ";
         cin.getline(joining_DATE,20);
         cout<<" Job Description: ";
         cin.getline(position,20);
         cout<<" Single / Married: ";
         cin.getline(marital_status,10);
         cout<<" Employee Age: ";
         cin.getline(age,10);
         cout<<" Salary Per Month: $ ";
         cin.getline(salary,20);
         cout<<" Comment: ";
         cin.getline(comment,80);
    }
 
 
     void showemp_data() //display Employee Data:
     {
     	cout<<"\n\nEMPLOYEE DATA: "<<endl;
     	cout<<"=================================\n"<<endl;
     	cout<<" Name: "<< name<<endl;
        cout<<" Employee ID: "<< employe_ID<<endl;
        cout<<" Position: "<< position<<endl;
        cout<<" Date of joining: "<< joining_DATE<<endl;
        cout<<" Age of Employee: "<< age<<endl;
        cout<<" Total Salary: $ "<< salary<<endl;
        cout<<" Maritial Status: "<< marital_status<<endl;
        cout<<" Comment: "<< comment<<endl;
    }
};
 
 
/*we are using this class to write data into 
  the file and read from file:*/
class Library
{
    public:
    	Employee Emp; //Employee class object:
    	fstream fp, fp1; //file object:
 
    	void WriteEmployee() //Write Employee data into the file:
    	{
           fp.open("Employe.txt",ios::out); //open file for writing:
           if(fp) // error chacker
     	   {
              Emp.getEmp_data(); //funtion calling.
              fp.write((char*)&Emp,sizeof(Emp)); //Write into file:
              cout<<"Record Store Successfully: "<<endl;
     	   } 
           fp.close();        
    	} 
 
    	void W_displayEmp() //display data from file:
	{
    	   fp.open("Employe.txt",ios::in); //Open same file for reading:
    	   if(fp) //error chacker
     	   {
         	while(fp.read((char*)&Emp,sizeof(Emp))) //read data form file:
		{
                	Emp.showemp_data(); //function calling
            	}
            	fp.close();
     	    }
	}
};
 
main()
{
    Library lib; //Library class object:
    lib.WriteEmployee(); //Write function calling:
    lib.W_displayEmp(); //display function calling:
 
    return 0;
}


Copy the code and paste it into your compiler, compile the Program, Enter your Data. after termination of Program, go to your folder where you compile your program and look for the "Employee.txt" file. open the file and look at your data that you store in it. You will find some ASCII code there. because the write() function uses the binary version of data instead of the text version.


Remove()

This function is used to Remove any file from record. It take one Argument, which is the file name to be delete. The basic syntax to use this function is-


remove(fileName);



Rename()

This function is used to rename any file. it take two argument. the first one is the old name of the file, and second, the new name for the file. The basic syntax to use this function is-


rename(Old_Name,  New_Name);



Let's have a example to know, how we can use these functions to remove and rename the file in C++ programming.


/*Remove(), Rename() function Example: InfoBrother*/
 
#include<fstream>//required for file operation:
#include<iostream>//required for input/output:
using namespace std;
 
main()
{
    fstream fp,fp1; //file pointer:
    char text[50]; //variable to store text from user:
    char ch;       //variable to read data from file:
 
    cout<<"Enter some Text here: "<<endl;
    cin.getline(text, 50);
 
    fp.open("InfoBrother.txt", ios::out); //file open for writing:
    if(fp) //error checker:
    {
        fp<<text;
        cout<<" file Create Successfully: "<<endl;
    }
    else cout<<" Error While Opening file: "<<endl;
    fp.close();
 
 
    fp.open("InfoBrother.txt", ios::in); //file open for reading:
    if(!fp) //error checker:
    {
        cout<< "Error While Opening File: "<<endl;
    }
 
    fp1.open("temp.txt", ios::out); //temporary file open for writing:
    if(!fp) //error checker:
    {
        cout<<" Error while Opening file: "<<endl;
    }
 
    while(fp.get(ch)) //read file:
    {
        fp1.put(ch); //copy file:
    }
    cout<<"\n Data Copy successfully to temp file: "<<endl;
 
    fp.close();
    fp1.close();
 
    rename("temp.txt", "Info.txt"); //rename "temp" to "Infobrother":
    cout<<"File rename successfully: "<<endl; 
 
    remove("InfoBrother.txt"); //remove InfoBrother file:
    cout<<"Old file Delete Successfully: "<<endl;     
 
    return 0;
}

Copy this code and paste it into your compiler. and run the program. enter your text and terminate the program. goto your folder and find "InfoBrother.txt" file, because you enter text in that file. but you won't find "InfoBrother.text" file. but you will find "info.txt" file there with your text:








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