Advertisement
File I/O Stream Classes | Description |
---|---|
ofstream | This class is used to create an output stream and gives access to put pointer, to perform the file write operation. |
fstream | This class is used to used to create an input-output stream and gives access to both get and put pointers, to the file read/write operations. |
file-stream-object("filename", mode);
File Mode | Description |
---|---|
ios::out | Searches for the file and opens it in write mode and gives access to put pointer to write the content to a file on disk. |
"ios::binary" | Searches for the file and opens the file(if the file is found) in a binary mode to perform binary input/output file operations. This mode when used with ios::binary, ios::in and ios::out modes, allows you to modify the content of a file |
Advertisement
Functions to use put pointer | Description |
---|---|
tellp() | Gives us the current location of the put pointer. When the file is opened in a write-only mode, tellg() returns zero i.e. the beginning of the file. |
seekp (streampos position ); | This function is used to set the location of the put pointer to a desired position/offset. The position variable is the new position in the file i.e. an integer value representing the number of bytes from the beginning of the file. |
seekp ( streamoff offset, ios_base::seekdir dir ); | This function is used to set the location of the put pointer to a desired position/offset. The position parameter is the new position in the file i.e. an integer value representing the number of bytes from the beginning of the file. The position parameter is relative to the dir parameter. dir is the seeking direction and it can take any of the constant values: ios::beg - offset from the beginning of the file. ios::cur - offset from the current position in the file. ios::end - offset from the end of the file. |
Gender : Male
Age : 28
City : Tokyo
Weight : 78.6 Kg
//Modifying the data to a file using fstream class and modes ios::out, ios::binary
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
//Creating an output stream to append new data to a file
fstream ofstream_ob;
//Opening a file named country1.txt to modify the old content
ofstream_ob.open("File1.txt", ios::in|ios::out|ios::binary);
char ch;
while(ofstream_ob)
{
ch = ofstream_ob.get();
if(ch =='e')
{
//Going one byte position back from the current put pointer position
ofstream_ob.seekp(-1, ios::cur);
ofstream_ob.put('X');
}
}
//closing the output stream
ofstream_ob.close();
return 0;
}
The modified content of the file :
GXndXr : MalX
AgX : 28
City : Tokyo
WXight : 78.6 Kg
ofstream_ob.seekp(-1, ios::cur);
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement