The
ifstream
class derives from the
istream
class, and enables users to access files and read data from them. The
ofstream
class derives from the
ostream
class, and enables users to access files and write data to them. The
fstream
class is derived from both the
ifstream
and
ofstream
classes, and enables users to access files for both data input and output. These functions are defined in the
fstream
header file.
Declaring input and ouput objects is simple.
#include <fstream>
using namespace std;
int main(void){
//input stream object
ifstream infile;
//output stream object
ofstream outfile;
return 0;
The open() function is a member of the ifstream or ofstream class; the function in its most basic form takes a single argument, the path to the desired file. We can check the ifstream or ofstream object directly as a binary value to test whether or not the file is open and the stream is read for I/O.
As second argument that can be sent to the open() member function is the mode, which is based on a set of predefined constants. The ios::in constant opens the file for reading, and the ios::out constant opens the file for writing.
We can use the seekg(), seekp(), tellg() and tellp() functions to enable random access of files. These functions change the position of an I/O stream pointer. The seekg() and tellg() functions are used with ifstream objects, and the seekp() and tellp() functions are used with ofstream objects.
#include <iostream>
#include <fstream>
using namespace std;
int main(void){
ifstream infile;
ofstream outfile;
int i = 0;
char ch;
infile.open("test.txt");
outfile.open("test_partial.txt");
if(infile && outfile){
infile.seekg(15);
while(infile.get(ch)){
outfile.put(ch);
infile.close();
outfile.close();
return 0;
Posted in Uncategorized and tagged ifstream, ofstream, seekg() on by aljensen.
Leave a comment
Privacy & Cookies: This site uses cookies. By continuing to use this website, you agree to their use.
To find out more, including how to control cookies, see here:
Cookie Policy