The C++ file input and output: using the write(), seekp(), tellp(), open(), close() member functions in C++ program


Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info: none

To do: Using the write(), seekp(), tellp(), open(), close() member functions in C++ programming

To show: How to use the write(), seekp(), tellp(), open() and close() member functions in C++ programming




// using the seekp() and tellp() member functions

#include <iostream>

#include <fstream>

using namespace std;


void main(void)


// provide a full path if needed

char filename[ ] = "C:\\testfileio4.txt";

ofstream outputfile;

int locate;


// creating, opening and writing data to a file, ios::out);


// simple error handling for file creating/opening test if fail to open



cout<<"Creating and opening "<<filename<<" file for writing\n";


cout<<"The "<<filename<<" file could not be created/opened!\n";

cout<<"Possible errors:\n";

cout<<"1. The file does not exist.\n";

cout<<"2. The path was not found.\n";

exit(1); // just exit

// 0-normal, non zero - some error


// if successful creating/opening the file



cout<<"The "<<filename<<" file was created and opened successfully!\n";

cout<<"\nDo some file writing....\n\n";

outputfile.write("Testing: Just simple example.", 29);


// tell the pointer position

locate = outputfile.tellp();


// seek the pointer position with offset



// write for 7 length

outputfile.write(" rumble", 7);

// close the output file



// simple error handling for output files closing test if fail to close the file, do...



cout<<"The "<<filename<<" file could not be closed!\n";



// if successful to close the file


cout<<"\nThe "<<filename<<" file was closed successfully!\n";




Output example:


The C:\testfileio4.txt file was created and opened successfully!

Do some file writing....

The C:\testfileio4.txt file was closed successfully!

Press any key to continue . . .


The testfileio4.txt file content is shown below.



Testing: Just rumble example.



C and C++ Programming Resources | C & C++ Code Example Index