首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >tellp在C++中的使用

tellp在C++中的使用
EN

Stack Overflow用户
提问于 2010-08-23 13:34:43
回答 2查看 5.3K关注 0票数 0

我对tellpseekg函数有一些误解。例如,当我运行以下代码时。

代码语言:javascript
复制
#include <iostream>
#include <ostream>
#include <fstream>
using namespace std;
int main(){
    string 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;
}

结果如下。

代码语言:javascript
复制
pointer 0
pointer 1 i
pointer2 n
pointer  3
pointer 4 -g
........

诸若此类。据我所知,第一个指针是文件,然后指向字符串中的第一个字符,依此类推。

现在考虑以下代码。

代码语言:javascript
复制
#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;
}

结果是:

代码语言:javascript
复制
This is a sample

这一行,pos = outfile.tellp();,我认为和第一个例子一样,pos变成了0。在这段代码中,outfile.seekp (pos-7)是什么意思?指向-7或?的指针

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-08-23 14:07:12

tellp给出put指针的当前位置。outfile.seekp (pos-7)语句将put指针从其当前位置向后移动7个字节。在您的示例中,它指向字符串"This is an apple“之外。如果执行pos-7,它将指向'n‘字母所在的位置。它会覆盖那里的字符串“sam”。所以结果字符串变成了"This is a sample“

票数 2
EN

Stack Overflow用户

发布于 2010-08-23 14:11:14

示例是here

在同一页上:

在本例中,tellp用于获取写入操作后put指针的位置。然后指针向后移动7个字符以修改该位置的文件,因此文件的最终内容应为:这是一个示例

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3544965

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档