こんにちは親愛なる親切な人々
クラスのseekg()
関数を使用して問題が発生しました。ifstream
私の目標は、既知のレイアウトでテキスト ファイルから整数を読み取ることです。以下は、Ph_Sn.cfg という名前のファイルの例です。
some random text bla bla
48 molecules of all types
much more text
and numbers etc etc
実際のプログラムでは、ファイルを開いて複数のタスクを実行しているため、読み取り位置を少し移動する必要があります。私は自分の問題を追跡し、以下のコードである最小限の実例を作成しました。
要するに、関数を呼び出してストリームカーソルを移動するseekg()
と、ストリームオブジェクトが何らかの形で破損し、次の >> 演算子にフェイルビットが設定されます。
#include <iostream>
#include<fstream>
using std::ifstream;
using std::cin;
using std::cout;
using std::endl;
using std::ios;
int skipline(ifstream&);
int main() {
char *file_name = "Ph_Sn.cfg";
ifstream file;
int input;
file.open(file_name);
skipline(file); //skipping a certain amount of lines (here: 1) since I know the file layout
const ifstream::streampos correctPosition = file.tellg(); //stream position before the integer I want to read
file>>input;
cout<<"Integer of interest: "<<input<<endl; //check if integer was read correctly
file.seekg(ios::beg); //revert to start of the file, just for demonstration in this example
skipline(file);
cout<<"good flag, failbit, badbit, eof = "<<file.good()<<" "<<file.fail()<<" "<<file.bad()<<" "<<file.eof()<<endl; //checking flags just for demonstration
file.seekg(correctPosition); //if this line is commented out, the second reading succeeds
cout<<"after seekg comparison tellg==correctPosition "<<(file.tellg()==correctPosition)<<endl; //after calling seekg the position is still correct
cout<<"after seekg: good flag, failbit, badbit, eof = "<<file.good()<<" "<<file.fail()<<" "<<file.bad()<<" "<<file.eof()<<endl; //checking again, still no errors
file>>input; //attempt to read out the integer again
cout<<"Integer of interest: "<<input<<endl;
cout<<"good flag, failbit, badbit, eof = "<<file.good()<<" "<<file.fail()<<" "<<file.bad()<<" "<<file.eof()<<endl; //the >> operator set the fail flag
cin>>input; //I don't want the console to close to see the output
return 0;
}
int skipline(ifstream &file)
{
int code;
if(!file)
return(0);
else
{
do
{
code=file.get();
}
while (code!=10);
}
return(1);//no error
}
コードをコンパイルし、Ph_Sn.cfg があるディレクトリで .exe ファイルを実行すると、コンソールに次の出力が表示されます。
Integer of interest: 48
good flag, failbit, badbit, eof = 1 0 0 0
after seekg comparison tellg==correctPosition 1
after seekg: good flag, failbit, badbit, eof = 1 0 0 0
good flag, failbit, badbit, eof = 0 1 0 0
Integer of interest: 0
コードのコメントで述べたように、操作をコメントアウトするだけ file.seekg(correctPosition);
で、2 回目の読み取りで正しい整数が得られます。
同様の問題に対する回答を見つけようとしましたが、ほとんどの場合、eof フラグが設定され、 を呼び出すことで問題が解決されましたfile.clear()
。残念ながら、これは私の場合には役に立たないようです。私もこの投稿を見つけましたが、私の問題は異なると思います (私はひどく間違っていますか?):
- Failbit は
seekg()
>> 演算子の直後ではなく直後に設定されます - 私のファイルはかなり小さいです(数kb)
- ファイルをテキストモードで開いています
問題はコード内にあるのではなく、Eclipse のセットアップにあるのではないかと思います。コードが機能するかどうか、独立してコンパイルされているかどうか、そしてもしそうなら、どのような設定がこの(私の目には)奇妙な動作の原因である可能性があるかを確認したいと思います。私は 32 ビットの Windows OS、cdt アドオンと MinGW GCC ツールチェーンを備えた eclipse-Luna を実行しています。
あらゆる種類のヘルプやヒントに感謝します。この問題は、今までに丸 1 週間占有されています。