1

ここにいる誰かが、read()呼び出しの後にC ++ ifstreamのgetポインターが破損する可能性がある方法を知っていますか?私は説明するのに途方に暮れているいくつかの本当に奇妙な行動を見ています。例(私が実際に実行しているものではなく、例示的なコード):

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 に答える