我注意到了这个奇怪的事情
fstream obj(filename , ios::in);
obj.seekp(7);
与
相同fstream obj(filename , ios::in);
obj.seekg(7);
seekg
和 seekp
执行相同的操作并导致相同的结果,尽管我仅指定了 ios::in 标志
为什么他们都使用 fstream? seekp
和 seekg
与 fstream 有什么区别?
最佳答案
basic_fstream
源自basic_iostream
,basic_iostream
源自basic_istream
和basic_ostream
。因此,basic_fstream
具有来自 basic_ostream
的函数 seekp
和来自 basic_ifstream
的函数 seekg
。
简而言之,在您的情况下,对 seekp 和 seekg 的调用执行相同的操作,因为 basic_filebuf::seekpos
执行的操作仅取决于 basic_filebuf
的打开模式>.
basic_ostream<charT,traits>& seekp(pos_type pos);
Effects: If fail() != true, executes rdbuf()->pubseekpos(pos, ios_base::out). In case of failure, the function calls setstate(failbit) (which may throw ios_base::failure).
在 pubseekpos
调用 seekpos
的地方(它是 virtual
,因此调用 basic_filebuf::seekpos
)
pos_type seekpos(pos_type sp,
ios_base::openmode which = ios_base::in | ios_base::out);
Alters the file position, if possible, to correspond to the position stored in sp (as described below). Altering the file position performs as follows:
if (om & ios_base::out) != 0, then update the output sequence and write any unshift sequence;
set the file position to sp;
3. if (om & ios_base::in) != 0, then update the input sequence;
where om is the open mode passed to the last call to open(). The operation fails if is_open() returns false.
由于您使用 ios_base::in
函数打开文件,因此会执行 2 和 3 个标点。
basic_istream<charT,traits>& seekg(pos_type pos);
Effects: Behaves as an unformatted input function (as described in 27.7.2.3, paragraph 1), except that the function first clears eofbit, it does not count the number of characters extracted, and it does not affect the value returned by subsequent calls to gcount(). After constructing a sentry object, if fail() != true, executes rdbuf()->pubseekpos(pos, ios_base::in). In case of failure, the function calls setstate(failbit) (which may throw ios_base::failure).
关于c++ - 使用 fstream 进行 seekp 和 seekg,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12334730/