繁体   English   中英

C ++ tellg()返回类型

[英]C++ tellg() return type

我有一个大的二进制文件,我正在阅读,我想比较当前位置与unsigned long long int。 但是,基于C ++文档,我不清楚是否:

  1. 什么是tellg()的返回类型
  2. 如何将tellg()与unsigned long long int进行比较?
  3. 是否有可能tellg()的返回类型具有小于unsigned long long int的最大值(来自numeric_limits)?

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

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

A istream::tellg()的返回类型是streampos 看看std :: istream :: tellg

问:如何将tellg()与unsigned long long int进行比较?

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

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

看看std :: streampos

:tellg()的返回类型是否有可能小于unsigned long long int的最大值(来自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 (读作“stream offset”)作为整数类型来存储tellg()的结果。

从浏览std :: basic_ifstream

pos_type tellg();

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

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

(由我完成的粗体)

因此,为了避免溢出,将tellg()的结果tellg()std::streamoff tellg()的类型应该是安全的。 此外,检查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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM