I'm not exactly sure whether I have the concept of tellp() tellg() and seekg() seekp() right. I'm assuming it is to get a specific position in the file and assigns the position to a pointer. But my question is.. what can i do with the pointer? can i edit the text inside the file where the pointer points to?
I already went to the tutorials in this website about the use of tellp() and tellg() but I don't fully understand it. If anyone can enlighten me about this I would truly appreciate it.
#include <iostream>
#include <fstream>
#include <string>
usingnamespace std;
int main ()
{
streampos position; //declaring position
string string1;
fstream file; // declaring file object
file.open ("secret.txt", ios::in | ios::out | ios::app);
file.seekp (5 ,ios::beg); //seeks the exact position in the file
position = file.tellp(); //assigning current position to the position object
if(file.is_open())
{
cout << "File has been open" << "\n";
}
else
cout << "ERROR, file can't be found";
while (getline (file,string1))
{
cout << string1 << "\n";
}
cout << position;
This is my code that I wrote that opens a file called secrets.txt, and im using tellp() and seekp() to point to a specific position of the file. But every time I increase the offset it just removes the first text in the output. Any criticisms are welcomed.
streampos is just an integer. tellg/tellp tell you the location you can currently read/write from/to in the file in terms of characters from the start of the file. seekg/seekp move that location to a position you specify.
Note that if you write to a non-empty file from a location other than the end, you will overwrite the characters already there. There is no way to directly insert characters into the middle of a file.
One of the first things I see is that the location of the seekp() and tellp() calls should be after you check if the file opened correctly.
Next it would be better in this situation to play with the seekg() and tellg() functions instead. Create a file that contains this line: "This is a test of the seekp() and tellg() functions." Then enter and run the following code.