gpt4 book ai didi

c++ - c++中tellp的使用

转载 作者:行者123 更新时间:2023-11-27 22:30:13 25 4
gpt4 key购买 nike

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

#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;
}

结果如下。

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

等等。据我了解,第一个指针 0 它只是文件指针,然后指向字符串中的第一个字符,依此类推。

现在考虑以下代码。

#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;
}

结果是:

This is a sample

这一行,pos = outfile.tellp();,我认为与第一个示例一样,pos 变为零。在此片段中,outfile.seekp (pos-7) 是什么意思?指向-7 或?

最佳答案

例子是here

来自同一页面:

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

关于c++ - c++中tellp的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3544965/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com