このバイナリ リーダーは、インターネットでのチュートリアルの後に作成しました。(リンク先を探しています…)
このコードはファイルを 1 バイトずつ読み取り、最初の 4 バイトはまとめてマジック ワードです。(MAGIとしましょう!)私のコードは次のようになります:
std::ifstream in(fileName, std::ios::in | std::ios::binary);
char *magic = new char[4];
while( !in.eof() ){
// read the first 4 bytes
for (int i=0; i<4; i++){
in.get(magic[i]);
}
// compare it with the magic word "MAGI"
if (strcmp(magic, "MAGI") != 0){
std::cerr << "Something is wrong with the magic word: "
<< magic << ", couldn't read the file further! "
<< std::endl;
exit(1);
}
// read the rest ...
}
ここで問題が発生します。ファイルを開くと、次のエラー出力が表示されます。
Something is wrong with the magic word: MAGI?, couldn't read the file further!
つまり、この例の文字のように、MAGI という単語の後に常に 1 つの (ほとんどランダムな) 文字があります?
。C++ の文字列がどのように格納され、相互に比較されるかに関係があると思います。私は正しいですか、どうすればこれを回避できますか?
PS: この実装は別のプログラムに含まれており、まったく問題なく動作します ... 奇妙です。