# C++ File Stream Classes

File streams are the libraries which are utilized in programming. These use the iostream preferred standard library because it offers cin and cout strategies which are used for analyzing from the input and writing to the output respectively.

A file is a collection of associated data stored in a particular area on a disk.

The data transfer can take place in bi-directional ways,

1. Data switch between the console unit and the program.

2. Data switch between the program and a disk file.

### What are the file stream classes?

A file stream can be described by using the  ifstream, ofstream, and fstream classes that are contained in the header file fstream.

The class to be used depends upon the purpose whether the write data or read data operation is to be executed on the file.

By Using iostream standard library, for reading from input and writing to output it provides cin and cout methods.

Operations in File Handling:

• Creating a file: open()
• Reading data: read()
• Writing new data: write()
• Closing a file: close()

To read and write from a file we are using the standard C++ library known as fstream

Fstream: It is used to create files, writes information to files, and read information from files.

This class provides maintenance for both input and output operations on the files at the same time. It inherits all the member functions of the istream and ostream classes via iostream class. when a file is opened in default mode, it also contains the open() function.

Ifstream: It is used to read information from files. This class supports input operations on the files

It inherits the features get( ), getline( ), read( ), seekg( ) and tellg( ) from istream class. When the file is opened in default mode, it contains open( ) function.

#### The functions of ifstream class are :

(i) get()

This function is used to read a single character from the file. The get pointer specifies the character which has to be read from the file.

(ii) getline()

This function reads a line of text which results up with a newline character. It can be called using cin object as regard to,

cin.getline( line, size)

Where the line is a variable that reads a line of text.

Size is many characters to be read getline() function reads the input until it encounters ‘\n’ or size ⎼1 character is read. It is not saved instead it is replaced by the null character.

(iii) read()

This function scans for a block of data of length specified by an argument ‘n’. This function reads data sequentially. So when the Ending of the function is reached before the whole block is read then the buffer will contain the elements read until the End of the function.

#### General Syntax

istream & read(char*str, size n);

(iv) seekg()

This function is used to shift the input pointer (i.e., get) to the given location. It belongs to ifstream. It is a file manipulator.

(v) tellg()

This function is used to shift the current position of the input pointer. It belongs to the ifstream class.

Ofstream: It is used to create files and write information to the files.

This class helps output operations on the files. It inherits the functions put(), seekp(), tellp() and write() from ostream class. When the file is opened in default mode, it also includes the open() function.

#### The functions of ofstream class are mentioned below,

(i) put();

This function is used to write a single character to the file. A stream object specifies to which file the character should be written. This individual will be located at the position specified by the put pointer. This function belongs to fstream class.

(ii) seekp()

This function is used to shift the output pointer that is gi ‘\n’ven location. It belongs to the ofstream class. It is likewise a file manipulator.

(iii) tellp()

This function is used with output streams and returns the current “put” position of the pointer in the stream.

It has no parameters and returns a value of the member type pos_type, which is an integer data type representing the current position of the put stream pointer.

(iv) write()

This function presents a line on the screen. It is used by cout object as follows,

cout.write(line, size)

Where the line is the string to be displayed.

Size is the number of characters to be displayed.

If the size of a string is greater than the line (i.e., text to be displayed) then the write() function stops displaying on encountering a null character but displays beyond the bounds of the line.

File streams are the libraries which are utilized in programming. These use the iostream preferred standard library because it offers cin and cout strategies which are used for analyzing from the input and writing to the output respectively.

A file is a collection of associated data stored in a particular area on a disk.

The data transfer can take place in bi-directional ways,

1. Data switch between the console unit and the program.

2. Data switch between the program and a disk file.

To read and write from a file we are using the standard C++ library known as fstream

(i) get()

This function is used to read a single character from the file. The get pointer specifies the character which has to be read from the file.

(ii) getline()

This function reads a line of text which results up with a newline character. It can be called using cin object as regard to,

cin.getline( line, size)

Where the line is a variable that reads a line of text.

Size is many characters to be read getline() function reads the input until it encounters ‘\n’ or size ⎼1 character is read. It is not saved instead it is replaced by the null character.

(iii) read()

This function scans for a block of data of length specified by an argument ‘n’. This function reads data sequentially. So when the Ending of the function is reached before the whole block is read then the buffer will contain the elements read until the End of the function.

General syntax,

istream & read(char*str, size n);

(iv) seekg()

This function is used to shift the input pointer (i.e., get) to the given location. It belongs to ifstream. It is a file manipulator.

(v) tellg()

This function is used to shift the current position of the input pointer. It belongs to the ifstream class.

Ofstream: It is used to create files and write information to the files.

This class helps output operations on the files. It inherits the functions put(), seekp(), tellp() and write() from ostream class. When the file is opened in default mode, it also includes the open() function.

### What Are Functions Of ofstream class?

The functions of ofstream class are mentioned below,

(i) put();

This function is used to write a single character to the file. A stream object specifies to which file the character should be written. This individual will be located at the position specified by the put pointer. This function belongs to fstream class.

(ii) seekp()

This function is used to shift the output pointer that is gi ‘\n’ven location. It belongs to the ofstream class. It is likewise a file manipulator.

(iii) tellp()

This function is used with output streams and returns the current “put” position of the pointer in the stream.

It has no parameters and returns a value of the member type pos_type, which is an integer data type representing the current position of the put stream pointer.

(iv) write()

This function presents a line on the screen. It is used by cout object as follows,

cout.write(line, size)

Where the line is the string to be displayed.

Size is the number of characters to be displayed.

If the size of a string is greater than the line (i.e., text to be displayed) then the write() function stops displaying on encountering a null character but displays beyond the bounds of the line.

FileStream Writing to a File

Example #1

#include <iostream>
#include <fstream>
using namespace std;
int main () {

ofstream filestream("testout.txt");

if (filestream.is_open())

{
filestream << “Example for \n";
filestream << "Writing to File\n";
filestream.close();

}

else cout <<"File does not open";

return 0;
}


Output

The content of a text file testout.txt is set with the data:
Example for
Writing to File


The content of a text file testout.txt is set with the data:

Example for

#### Opening a  File:

A file must be opened before you can read from it or write to it. Either the ofstream or fstream object may be used to open a file for writing and ifstream object is used to open a file for reading purposes only.

You can combine two or more of these values by ORing them together.

For example: If you want to open a file in write mode and want to truncate it in case that already exists, the following will be the syntax –

ofstream outfile;

outfile.open("file.dat", ios::out | ios::trunc );

Same as we can open a file for reading and writing purposes as follows

fstream afile;

afile.open(“file.dat”, ios::out | ios::in );

#### Closing a File:

When a program terminates it automatically removes all the streams, releases all the allocated memory, and closes all the opened files. But it is always a good practice to close all the opened files before program termination.

Following is the standard syntax for close() function, which is a member of fstream, ifstream, and ofstream objects.

void close();

Example #2 – Closing a File

#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile;
myfile.open ("study.txt");
if(myfile.is_open()){
cout<<"File opened"<<endl;
myfile.close();//file close
cout<<"File Closed."<<endl;
}
else{
cout<<"Error in file opening"<<endl;
}
return 0;
}


Output:

File opened
File Closed


### File Position Pointers

Both istream and ostream provide member functions for repositioning the file-position pointer. These member functions are seekg (“seek get”) for istream and seekp (“seek put”) for ostream.

The argument to seekg and seekp normally is a long integer. A second argument can be specified to indicate the seek direction. The seek direction can be ios::beg (the default) for positioning relative to the beginning of a stream, ios::cur for positioning relative to the current position in a stream, or ios::end for positioning relative to the end of a stream.

The file-position pointer is an integer value that specifies the location in the file as several bytes from the file’s starting location. Some examples of positioning the “get” file-position pointer.

• position to the nth byte of fileObject (assumes ios::beg)

fileObject.seekg( n );

• position n bytes forward in fileObject

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

• position n bytes back from end of fileObject

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

• position at end of fileObject

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

Example #3

fin.seekg(20, ios::beg);   // go to byte no. 20 from beginning of file

fin.seekg(-5, ios::cur);   // back up 5 bytes from the current position of

fin.seekg(0, ios::end);      // goes to the end of the file

fin.seekg(-9, ios::end);   // backup 9 bytes from the end of the file


### Summary

The file stream has all the built-in functions to create, manipulate files using C++ programming. The article introduced the capabilities of C++ programming. Therefore, in the next article you can learn about file pointers, file manipulation in more detail.