Q:

C++ tellg(), seekg() and seekp() Example

belongs to collection: C++ programs on various topics

-1

C++ tellg(), seekg() and seekp() Example

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program:

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

int main()
{
    fstream F;
    // opening a file in input and output mode
    F.open("my.txt", ios::in | ios::out);
    
    // getting current location
    cout << F.tellg() << endl;
    
    // seeing 8 bytes/characters
    F.seekg(8, ios::beg);
    // now, getting the current location
    cout << F.tellg() << endl;
    // extracting one character from current location
    char c = F.get();
    // printing the character
    cout << c << endl;
    
    // after getting the character,
    // getting current location
    cout << F.tellg() << endl;
    // now, seeking 10 more bytes/characters
    F.seekg(10, ios::cur);
    // now, getting current location
    cout << F.tellg() << endl;
    // again, extracing the one character from current location
    c = F.get();
    // printing the character
    cout << c << endl;
    
    // after getting the character,
    // getting current location
    cout << F.tellg() << endl;
    // again, seeking 7 bytes/characters from beginning 
    F.seekp(7, ios::beg);
    // writting a character 'Z' at current location
    F.put('Z');
    // now, seeking back 7 bytes/characters from the end
    F.seekg(-7, ios::end);
    // now, printing the current location
    cout << "End:" << F.tellg() << endl;
    // extracting one character from current location
    c = F.get();
    // printing the character
    cout << c << endl;
    
    // closing the file
    F.close();
    return 0;
}

Output

0
8
e
9
19
i
20
End:93
s

After the program execution the file content is,

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C++ programs on various topics

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C++ program for Banking Management System using Cl... >>
<< C++ | Create a class with setter and getter method...