1

这里有人知道 C++ ifstream 的 get 指针在 read() 调用后可能会损坏吗?我看到了一些我无法解释的真正奇怪的行为。例如(说明性代码,而不是我实际运行的代码):

int main()
{
   // datafile.bin is a 2MB binary file...
   std::ifstream ifs( "datafile.bin", ios::binary );
   ifs.exceptions ( ifstream::eofbit | ifstream::failbit | ifstream::badbit );

   int data[100];

   std::istream::pos_type current_pos = ifs.tellg();
   // current_pos = 0, as you'd expect...

   ifs.read( reinterpret_cast<char*>(data), 100 * sizeof(int) );
   // throws no exception, so no error bits set...

   std::streamsize bytes_read = ifs.gcount();
   // gives 400, as you'd expect...

   current_pos = ifs.tellg();
   // current_pos = 0x1e1a or something similarly daft

   return 0;
}

我的示例显示了一个数组读取,但即使在读取内置类型的单个值时也会发生这种情况;读取之前的 get 指针是正确的, gcount() 调用报告读取的正确字节数,但之后的 get 指针完全搞砸了。每次 read() 调用都不会发生这种情况——有时我会在一个东西出现之前通过一堆它们。什么可能会与 get 指针混淆?我在做一些非常愚蠢的事情吗?

任何和所有的帮助都非常感谢......

西蒙

4

2 回答 2

1

pos_type不是整数类型而是一个类,我不会试图解释它的表示。它可以隐式转换为整数类型,但如果您在调试器中查看它,您将看到内部表示。

于 2010-06-23T11:52:34.233 回答
0

我尝试在 Vista 机器上的 VS 2008 中运行您的代码,但没有收到任何错误。我已经修改了您的代码以在控制台上打印。

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
   // datafile.bin is a 2MB binary file...
   std::ifstream ifs( "H_Line.bmp", ios::binary );
   ifs.exceptions ( ifstream::eofbit | ifstream::failbit | ifstream::badbit );

   int data[100];

   std::istream::pos_type current_pos = ifs.tellg();

   cout<<current_pos<<endl; // current_pos = 0, as mentioned


   ifs.read( reinterpret_cast<char*>(data), 100 * sizeof(int) );
   // throws no exception, so no error bits set...

   std::streamsize bytes_read = ifs.gcount();

   cout<<bytes_read<<endl; // gives 400, as you have mentioned

   current_pos = ifs.tellg();

   cout<<current_pos<<endl; // FOR ME IT IS GIVING 400


   return 0;
}

我已经在大小 > 20 MB 的 BMP 图像文件上对此进行了测试

您能否详细说明您正在使用哪台机器/编译器。谢谢

于 2010-06-23T11:52:03.473 回答