C++ Read Data From Specified Position in File Using Seekg
Posted by Samath
Last Updated: January 05, 2017

The aim of this program is to read data from specified position in a file using seekg. seekg is a function in the iostream library (part of the standard library) that allows you to seek to an arbitrary position in a file. This function is defined for istream class.

#include <iostream> 
#include <fstream>  
using namespace std;

int main()
{
    
  int array_size = 1000; 
	char * array = new char[array_size]; 
	int position = 0;

	ifstream fin("myfile.txt",ifstream::binary);
	if(fin.is_open()) 
	{
		fin.seekg(0, ios::end); 
		int length = fin.tellg(); 
		fin.seekg(0,ios::beg); 
		cout << "Please Enter Position:(0-" << length << "):";
		int seek_position;
		cin >> seek_position;

		if(seek_position >= 0 && seek_position <= length) 
		{
			fin.seekg(seek_position,ios::beg); 
			while(!fin.eof())
			{
				fin.get(array[position]);
				position++;
			}
			array[position-1] = '\0';
			for(int i = 0; array[i] != '\0'; i++)
			{
				cout << array[i];
			}
		}
		else 
		{
			cout << "Invalid Seek Position." << endl;
		}
		
	}
	else 
	{
		cout << "File could not be opened." << endl;
	}
  
	return 0;
}