C++ tellg() 返回类型
C++ tellg() return type
我正在读取一个大的二进制文件,我想将当前位置与无符号长整型进行比较。但是,根据C++文档,我不清楚是否:
- tellg(( 的返回类型是什么
- 如何将 tellg(( 与无符号长整型进行比较?
- 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_type
由Traits
模板参数定义,而模板参数又是实现定义的。对于 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
- 如何获取std::result_of函数的返回类型
- 奇怪的结构&GCC&clang(void*返回类型)
- 如何建立使用模板函数的lambda函数的尾部返回类型
- 为什么与常规GCC不同,即使有"学究性错误",MinGW-GCC也能容忍丢失的返回类型
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- 特征::矩阵<双精度,1,3> 结构类型函数中的返回类型函数
- 函数作为模板参数,是否对返回类型强制约束
- C++中函数的向量返回类型引发错误
- 检查函数返回类型是否与STL容器类型值相同
- 为什么返回类型中需要typename?C++
- <Windows>为什么 std::thread::native_handle 返回类型为"long long unsigned int"的值,而不是 void*(又名 HANDLE)?
- 警告:在函数返回类型 [-Wignore 限定符] 时忽略类型限定符
- 为什么 c++(g++) 不允许模板返回类型和函数名称之间有空格?
- 为什么返回类型的'const'限定符对标有 __forceinline/内联的函数没有影响?
- 推导 std::vector::back() 的返回类型
- 在 c++ 中将函数返回类型指定为模板参数
- 使用 SWIG 更改生成的 CS 函数中的返回类型
- QtQuick - qml:28:错误:未知方法返回类型:自定义类型
- 如何收集和存储 tellp(), tellg() 返回类型
- C++ tellg() 返回类型