C++ C++;:file.seekg()似乎不返回当前位置
我正在尝试备份ifstream中的一行C++ C++;:file.seekg()似乎不返回当前位置,c++,c++11,fstream,seekg,C++,C++11,Fstream,Seekg,我正在尝试备份ifstream中的一行file.tellg()正在返回一个我不期望的值。在下面的示例中,在读取第一行(15个字符的字符串长度)后,我希望file.tellg()返回16。相反,它正在返回41。有人能提供一些关于这种行为的见解吗 test.cpp #include <fstream> #include <ios> #include <string> #include <iostream> using namespace std; i
file.tellg()
正在返回一个我不期望的值。在下面的示例中,在读取第一行(15个字符的字符串长度)后,我希望file.tellg()返回16。相反,它正在返回41。有人能提供一些关于这种行为的见解吗
test.cpp
#include <fstream>
#include <ios>
#include <string>
#include <iostream>
using namespace std;
int main(){
ifstream file("sample.ics", ios::in);
string line;
string key0;
string key1;
string value0;
string value1;
getline(file, line, '\n');
cout << "line = " << line << endl;
cout << "line.length = " << line.length() << endl; // should be 15;
cout << "Attempt:" << endl;
int pos = file.tellg(); // should be 16;
cout << " pos = " << pos << endl;
getline(file, key0, ':');
getline(file, value0, '\n');
cout << " First:" << endl;
cout << " " << key0 << ":" << value0 << endl;
cout << " backing up..." << endl;
file.seekg(pos, ios_base::beg);
getline(file, key1, ':');
getline(file, value1, '\n');
cout << " Second:" << endl;
cout << " " << key1 << ":" << value1 << endl;
file.close();
}
样本
BEGIN:VCALENDAR
CALSCALE:GREGORIAN
VERSION:2.0
METHOD:PUBLISH
...
尝试以二进制模式打开文件,看看是否得到相同的结果:
ifstream文件(“sample.ics”,ios::binary)
std::istream::tellg()
不返回int
,而是返回std::streampos
:是否尝试使用此类型还原位置?我尝试了上面的代码。在我的电脑上,它的pos=16
可能是一个行尾兼容性问题。看,和。streampos仍然是41。同样的结果在二进制模式下打开时可能会弄乱以文本形式读取文件的过程,尽管这是正常的。您必须使用std::streampos
而不是int
BEGIN:VCALENDAR
CALSCALE:GREGORIAN
VERSION:2.0
METHOD:PUBLISH
...