开发者

Usage of tellp in C++

I have some misunderstanding about the tellp and seekg functions. For example, when I run the following code.

#include <iostream>
#include <ostream>
#include <fstream>
using namespace std;
int main(){
    s开发者_C百科tring s("in Georgia we are friends 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 the first character in the string and so on.

Now consider the 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;
}

The result is:

This is a sample

This line, pos = outfile.tellp();, I think gets pos to zero as in the first example. In this fragment, what does outfile.seekp (pos-7) mean? Pointer to -7 or?


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


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"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜