File pointers

aka Stream pointer.

 

Each file stream class has a pointer that points to the current read/write position in the file.

 

Default position when opening a file for reading/writing is at the beginning of the file, unless in append mode in which case the file pointer is moved to the end of the file in order not to overwrite any current data.

 

The file input seekg() and file output seekp() methods require two parameters that firstly specify how many bytes to move the file pointer and the secondly an ios flag that specifies where to offset from:

  • beg - Offset is relative to the beginning of the file (default)
  • cur - Offset is relative to current position
  • end - Offset is relative to the end of the file

A positive offset means move the file pointer forward towards the end of the file, whilst a negative offset means move the file pointer backward towards the beginning of the file.

 

Using the previously made testFile.dat, this example reads out the lines from the specified file pointer positions:

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

void printLine(ifstream &myFile, string myString) {
	getline(myFile, myString) ;
	cout << myString << endl ;
}

int main () {

	ifstream myFile("testFile.dat") ;

	if (!myFile){
		cerr << "Couldn't open file for reading." ;
		return 1 ;
	}

	string myString ;

	myFile.seekg(7) ; //more file pointer to 7th character
	printLine(myFile, myString);

	myFile.seekg(6, ios::cur) ; //more file pointer 6 more characters forward
	printLine(myFile, myString);

	myFile.seekg(0, ios::beg) ; //more file pointer to beginning of file
	printLine(myFile, myString);

	myFile.seekg(-41, ios::end) ; //more file pointer 6 more characters forward
	printLine(myFile, myString);

	return 0;
}

Compile & Run:

t another line of amazing text
xt...
Wow, yet another line of amazing text
OK this really is the last line of text

 

 

Two further functions, tellg() and tellp() take no parameters and return the position of the file pointer:

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

int main () {

	ifstream myFile("testFile.dat") ;

	if (!myFile){
		cerr << "Couldn't open file for reading." ;
		return 1 ;
	}

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

	cout << "The file size is: "<< myFile.tellg() << "Bytes" << endl ;

	return 0;
}

Compile & Run:

The file size is: 220Bytes

Leave a Reply