gpt4 book ai didi

c++ - 从 istream 读取后,如何将光标设置回预读位置?

转载 作者:太空宇宙 更新时间:2023-11-04 11:48:00 25 4
gpt4 key购买 nike

我正在修改二进制数据 的读取例程。不幸的是,我不再那么坚定地使用 C++,这是编写例程的语言。例程开始读取一些数据。之后,我希望它查看缓冲值,我也从文件中读取了该值。 根据值,代码应该执行某些操作并在之后正常继续撤消读取缓冲区并正常继续。

我的问题是撤消或恢复光标位置(如果您愿意的话)。剥离的代码看起来像这样:

int buffer;

std::fstream inputFile;
inputFile.open( "Filename", std::ios::in | std::ios::binary );

... // read some data from inputFile

// read buffer value
inputFile.read( reinterpret_cast<char *>(&buffer), sizeof(buffer) );

if( buffer == 256 ) {
... // do something here
} else
// make it so nothing (including reading the buffer earlier) happened
inputFile.seekg( -1*sizeof(buffer), std::ios::cur ); // <---- is this right?
// or do I need to do it this way?
inputFile.seekg( -1*sizeof(buffer)/sizeof(char), std::ios:cur );
}

我假设我可以在 seekg() 中使用负值,因为我发现 int 只是合乎逻辑的,没有读到任何相反的东西。 上面哪种方式是正确的?或者基本上我是在问seekg() 实际上期望什么作为第一个参数?

C++ Reference只说这个:

 istream& seekg (streamoff off, ios_base::seekdir way); off    Offset value, relative to the way parameter.    streamoff is an offset type (generally, a signed integral type). way    Object of type ios_base::seekdir. It may take any of the following constant values:    value   offset is relative to...    ios_base::beg   beginning of the stream    ios_base::cur   current position in the stream    ios_base::end   end of the stream

哪个没有告诉我 off 的单位是(字节、字符、整数?)。

最佳答案

采用whence 参数的seekg() 版本采用std::streamoff 作为参数。它可以是负的。不需要除以 sizeof(char),因为 sizeof(char) 被定义为 1。由于流基于字符进行操作,因此流使用的单位是字符,即流的第一个模板参数的类型。

关于c++ - 从 istream 读取后,如何将光标设置回预读位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19317675/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com