tags:

views:

56

answers:

2
i  have some misunderstanding about tellp, seekg  ...  functions for example when i run following code

#include <iostream>
#include <ostream>
#include <fstream>
using namespace std;
int main(){
    string s("in georgia we  are friend to each other");
    ofstream out("output.txt");
    for (int i=0;i<s.length();i++){
        cout<<"file pointer"<<out.tellp();

        out.put(s[i]);
        cout<<" " <<s[i]<<endl;
    }
    out.close();



return 0;


}

the result is following

pointer 0 
pointer 1 i
pointer2 n
pointer  3
pointer 4 -g
........ 

and so on . as i understand first pointer 0 it is pointer just file then points to first character in string and so on now consider following code

  #include <fstream>
using namespace std;

int main () {
  long pos;

  ofstream outfile;
  outfile.open ("test.txt");

  outfile.write ("This is an apple",16);
  pos=outfile.tellp();
  outfile.seekp (pos-7);
  outfile.write (" sam",4);

  outfile.close();

  return 0;
}

it's result is

This is a sample 

this line

pos=outfile.tellp();  i think gets   pos to zero as in first example and    this fragment what means `outfile.seekp (pos-7)?;  pointer to -7  or?

please help thanks`

+1  A: 

tellp gives the current position of the put pointer. outfile.seekp (pos-7) statement moves the put pointer 7 bytes backwards from the its current position. In your example, it was pointing beyond the string "This is an apple" If you do pos-7, it goes to the location where 'n' letter is present. It overwrites the string " sam" from there. So the result string becomes "This is a sample"

bjskishore123
+2  A: 

The example is here

From the same page:

In this example, tellp is used to get the position of the put pointer after the writing operation. The pointer is then moved back 7 characters to modify the file at that position, so the final content of the file shall be: This is a sample

Chubsdad