我对tellp和seekg函数有一些误解。例如,当我运行以下代码时。
#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
........诸若此类。据我所知,第一个指针是文件,然后指向字符串中的第一个字符,依此类推。
现在考虑以下代码。
#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变成了0。在这段代码中,outfile.seekp (pos-7)是什么意思?指向-7或?的指针
发布于 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“
发布于 2010-08-23 14:11:14
示例是here
在同一页上:
在本例中,tellp用于获取写入操作后put指针的位置。然后指针向后移动7个字符以修改该位置的文件,因此文件的最终内容应为:这是一个示例
https://stackoverflow.com/questions/3544965
复制相似问题