我想要一些关于如何使用 seekg()
和 seekp()
在写文件时的澄清。例如,假设我有一个这样的文件:
offset 0: 2
offset 4: 4
offset 8: 6
offset 12: 8
offset 16: 10
现在我想要打开文件并执行一些查找以读取和写入值。
fstream file;
file.open("file.txt", fstream::in |fstream::out | fstream::binary);
file.seekp(0, ios::end) // seek to the end of the file
int eofOffset = file.tellp(); // store the offset of the end-of-file, in this case 20
int key = 0;
file.seekg(12, ios::beg); // set the seek cursor to offset 12 from the beginning of the file
file.read((char *) &key, (int)sizeof(int)); // read in the next 4 bytes and assign it to key, in this case 8
file.seekg(8, ios::beg); // set the seek cursor to offset 8 from the beginning of the file
file.read((char *) &key, (int)sizeof(int)); // read in the next 4 bytes and assign it to key, in this case 6
现在我想要将内容写入文件末尾。由于 seekg()
函数只移动了读指针,我的 seekp()
指针应该仍然位于文件末尾,对吗?所以:
int newKey = 12;
file.write((char *) &newKey, sizeof(int));
现在应该让我的文件看起来像:
offset 0: 2
offset 4: 4
offset 8: 6
offset 12: 8
offset 16: 10
offset 20: 12
如果我选择将文件指针移动到某个偏移并将该值作为新插入值的偏移写入,我的文件会发生什么?例如,我希望偏移量 8
保持eofOffset = 20
,因为我们刚刚在该偏移处插入了12。
如果我这样做:
file.seekp(8, ios::beg);
file.write((char *) &eofOffset, sizeof(int));
它是否正确地重写了我的文件,使其看起来像这样:
offset 0: 2
offset 4: 4
offset 8: 20
offset 12: 8
offset 16: 10
offset 20: 12
请告诉我,如果我在使用 seekg()
和 seekp()
函数时有任何错误,请指出。
seekg()
和seekp()
移动相同的指针,可以通过tellg()
和tellp()
来查看。 - Ben