C++ tellg() 返回类型

C++ tellg() return type

本文关键字:返回类型 tellg C++      更新时间:2023-10-16

我正在读取一个大的二进制文件,我想将当前位置与无符号长整型进行比较。但是,根据C++文档,我不清楚是否:

  1. tellg(( 的返回类型是什么
  2. 如何将 tellg(( 与无符号长整型进行比较?
  3. tellg(( 的返回类型是否有可能具有小于无符号长整型的最大值(从 numeric_limits 开始(?

任何答案或建议将不胜感激。

tellg(( 的返回类型是什么?

istream::tellg()的返回类型为 streampos 。查看 std::istream::tellg。

Q 如何将 tellg(( 与无符号长整型进行比较?

A tellg() 的返回值是整型类型。因此,您可以使用常用运算符来比较两个int。但是,您不应该这样做以从中得出任何结论。标准声称支持的唯一操作是:

这种类型的两个对象可以与运算符 == 和 != 进行比较。也可以减去它们,从而生成流类型的值。

查看 std::streampos。

:tellg(( 的返回类型是否有可能具有小于无符号长整型的最大值(从 numeric_limits 开始(?

A 该标准没有提出任何支持或反驳它的主张。它可能在一个平台上为真,而在另一个平台上为假。

附加信息

比较streampos,支持和不支持的比较操作示例

ifstream if(myinputfile);
// Do stuff.
streampos pos1 = if.tellg();
// Do more stuff
streampos pos2 = if.tellg();
if ( pos1 == pos2 ) // Supported
{
   // Do some more stuff.
}
if ( pos1 != pos2 ) // Supported
{
   // Do some more stuff.
}
if ( pos1 != pos2 ) // Supported
{
   // Do some more stuff.
}
if ( pos1 == 0 ) // supported
{
   // Do some more stuff.
}
if ( pos1 != 0) // supported
{
   // Do some more stuff.
}
if ( pos1 <= pos2 ) // NOT supported
{
   // Do some more stuff.
}

int k = 1200;
if ( k == pos1 ) // NOT supported
{
}

R Sahu 在回答问题方面做得很好,但是当.tellg()结果存储在int中时,我遇到了溢出,并做了一些额外的调查。

TL;DR:使用 std::streamoff(读作"流偏移"(作为整数类型来存储tellg()的结果。

从浏览标准::basic_ifstream:

pos_type tellg();

其中pos_typeTraits模板参数定义,而模板参数又是实现定义的。对于 std::ifstream,特征是 char 类型的 std::char_traits,这会导致 std::fpos。在这里我们看到:

fpos 类型的每个对象都保存流中的字节位置(通常作为 std::streamoff 类型的私有成员(和当前移位状态,即 State 类型的值(通常为 std::mbstate_t(。

(粗体由我完成(

因此,为了避免溢出,将tellg()的结果转换为任何类型的std::streamoff应该是安全的。此外,检查 std::streamoff 它说

类型std::streamoff是一个有符号的整数类型,其大小足以表示操作系统支持的最大可能文件大小。通常,这是一个长长的 typedef。


由于确切的类型由您的系统定义,因此运行快速测试可能是个好主意。这是我机器上的结果:

std::cout << "long long:" std::is_same<std::ifstream::off_type, long long>::value << std::endl;
std::cout << "long:" std::is_same<std::ifstream::off_type, long>::value << std::endl;
// Outputs
// long long:0
// long:1