Page 393 《编程:原理与实践》介绍了 seekg()
和 seekp()
,如下所示:
However, if you must, you can use positioning to select a specific place in a file for reading or writing. Basically, every file that is open for reading has a "read/get position" and every file that is open for writing has a "write/put position":
[diagram]
fstream fs {name}; // open for input and output if (!fs) error("can't open ", name); fs.seek(5); // move reading position to the 5 (the 6th character) char ch; fs >> ch; // read and increment reading position cout << "character[5] is " << ch << ' {' << int(ch) << "}\n"; fs.seekp(1); // move writing position to 1 fs << 'y'; // write and increment writing position
在代码片段中,“位置”以字符表示,例如:位置5被称为“第6个字符”。这让我很困惑,因为到目前为止,我们一直将文件视为字节序列,因此我期望位置以 字节 表示(在上面的示例中,我认为5是文件第6个字节的位置)。
因此,我尝试通过写入包含单个宽字符的文件的位置 1 来测试它:
wide.txt
௸
测试.cpp
#include "../std_lib_facilities.h"
int main() {
fstream fs {"wide.txt"};
fs.seekp(1);
fs << 'y';
fs.close();
return 0;
}
运行此代码后,wide.txt 如下所示:
�y�
似乎字符“y”被写入程序的第二个字节,而不是第二个字符,这意味着该位置指的是一个字节,而不是一个字符。 那么,为什么书中的代码片段会说“字符”呢?
我还注意到函数签名是 basic_ostream&eekp( pos_type pos );
(参见 CPP Reference ),但我找不到关于是否 pos_type
的解释指的是一个字符或一个字节。
cplusplus.com 上的引用似乎还根据字符定义位置(添加了强调):
Sets the position where the next character is to be inserted into the output stream.
就像下面的 comment 一样在 Reddit 帖子上(已添加重点):
A streampos IS NOT an integer, it's not some byte position in a stream. It represents a character position in the stream, and the type holds some stream state information for the purpose of code conversion and character position.
但这似乎与我在示例中看到的内容相矛盾,其中 fs.seekp(1)
似乎覆盖了字节 1(第二个字节)。
最佳答案
seekg()
和 seekp
对 code units 进行操作在 C++ 中,它们通常被称为“字符”,尽管后一个术语相当多,并且可能意味着其他含义。它们绝对不会对字节进行操作,如果您认为对于宽流,缓冲区元素具有 wchar_t
类型,那么很容易看出这一点。
引用https://en.cppreference.com/w/cpp/io/basic_streambuf :
The controlled character sequence (buffer) is an array of
CharT
which, at all times, represents a subsequence, or a "window" into the associated character sequence.
关于c++ - `seekg()` 和 `seekp()` 是对字符还是字节进行操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76241138/