c++中的tellp及tellg的有关问题
c++中的tellp及tellg的问题
#include <fstream>
#include <iostream>
using namespace std;
int main(){
fstream iofs("testpg.txt");
if(!iofs){
cout<<"open testpg.txt failed"<<endl;
}
cout<<iofs.tellp()<<endl;//输出结果为0
cout<<iofs.tellg()<<endl;//输出结果为0
cout<<"-----------------"<<endl;
iofs<<"hello";
iofs<<" ";
iofs<<123;
iofs.seekg(-3,ios::end);
int g;
iofs>>g;
cout<<iofs.tellp()<<endl; //输出结果为9
cout<<iofs.tellg()<<endl; //输出结果为-1
iofs.close();
}
tellp()及tell()指针指向的位置应为同一位置,上段程序中最后两句输出的为9和-1,
为什么不是9和9,求解?
------解决方案--------------------
iofs<<"hello"; // 5
iofs<<" "; // 1
iofs<<123; // 3
tellp()为9应该好理解
iofs.seekg(-3,ios::end); // 从流的末尾前3个位置开始get
int g;
iofs>>g; // 但读取了int 123,就会到流的末尾,即EOF -1?
#include <fstream>
#include <iostream>
using namespace std;
int main(){
fstream iofs("testpg.txt");
if(!iofs){
cout<<"open testpg.txt failed"<<endl;
}
cout<<iofs.tellp()<<endl;//输出结果为0
cout<<iofs.tellg()<<endl;//输出结果为0
cout<<"-----------------"<<endl;
iofs<<"hello";
iofs<<" ";
iofs<<123;
iofs.seekg(-3,ios::end);
int g;
iofs>>g;
cout<<iofs.tellp()<<endl; //输出结果为9
cout<<iofs.tellg()<<endl; //输出结果为-1
iofs.close();
}
tellp()及tell()指针指向的位置应为同一位置,上段程序中最后两句输出的为9和-1,
为什么不是9和9,求解?
------解决方案--------------------
iofs<<"hello"; // 5
iofs<<" "; // 1
iofs<<123; // 3
tellp()为9应该好理解
iofs.seekg(-3,ios::end); // 从流的末尾前3个位置开始get
int g;
iofs>>g; // 但读取了int 123,就会到流的末尾,即EOF -1?