c++ - 使用 fstream 进行 seekp 和 seekg

标签 c++ fstream

我注意到了这个奇怪的事情

fstream obj(filename , ios::in);
obj.seekp(7);

相同
fstream obj(filename , ios::in);
obj.seekg(7);

seekgseekp 执行相同的操作并导致相同的结果,尽管我仅指定了 ios::in 标志

为什么他们都使用 fstream? seekpseekg 与 fstream 有什么区别?

最佳答案

basic_fstream 源自basic_iostreambasic_iostream 源自basic_istreambasic_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:

  1. if (om & ios_base::out) != 0, then update the output sequence and write any unshift sequence;

  2. 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/

相关文章:

c++ - 模板成员函数的编译器错误

c++ - 正在重写的 fstream 文件

c++ - 排序和写入文件日期

c++ - 从 QThread 影响 QDialog

c++ - 将三字母语言代码转换为语言标识符 (LANGID)

c++ - 处理 vector - cudaMemcpyDeviceToHost

c++ - 如何使用 OpenGL 确保 Qt 中动画的适当速度?

c++ - Fstream 类 - 关于'>>'运算符的问题

c++ - 重定向 C++ fstream

c++ - 尝试加载文件 : Vector subscript out of range? 时出现运行时错误