C++: file.seekg() 没有出现在 return 当前位置
C++: file.seekg() does not appear to return current location
我正在尝试备份 ifstream 中的一行。 file.tellg()
是 returning 一个我没想到的值。在下面的示例中,在阅读第一行(长度为 15 个字符的字符串)后,我预计 file.tellg() 到 return 16。相反,它是 returning 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();
}
输出:
line = BEGIN:VCALENDAR
line.length = 15
Attempt:
pos = 41
First:
CALSCALE:GREGORIAN
backing up...
Second:
ION:2.0
sample.ics
BEGIN:VCALENDAR
CALSCALE:GREGORIAN
VERSION:2.0
METHOD:PUBLISH
...
尝试以二进制模式打开文件,看看是否得到相同的结果:
ifstream 文件("sample.ics", ios::binary);
我正在尝试备份 ifstream 中的一行。 file.tellg()
是 returning 一个我没想到的值。在下面的示例中,在阅读第一行(长度为 15 个字符的字符串)后,我预计 file.tellg() 到 return 16。相反,它是 returning 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();
}
输出:
line = BEGIN:VCALENDAR
line.length = 15
Attempt:
pos = 41
First:
CALSCALE:GREGORIAN
backing up...
Second:
ION:2.0
sample.ics
BEGIN:VCALENDAR
CALSCALE:GREGORIAN
VERSION:2.0
METHOD:PUBLISH
...
尝试以二进制模式打开文件,看看是否得到相同的结果:
ifstream 文件("sample.ics", ios::binary);