1

複数のデータ配列をファイルに書き込む際に、非常に奇妙な問題が発生しています。基本的に、すべての配列サイズをファイルの先頭に格納し、次に配列データを格納したいと考えています。このようにして、サイズを読み取るだけで、それを使用して配列を作成し、インポート時にデータを保持することができ、各配列の開始位置と終了位置を正確に知ることができます。

ここに問題があります。データを書き込みますが、インポートすると異なります。私の小さなテストコードを見てください。下部には、値に関するコメントがあります。

どうもありがとう、仲間のプログラマー!:)

#include <iostream>
#include <fstream>

int main()
{
    int     jcount = 100, // First item in file
            kcount = 200, 
            in_jcount,    // Third item in file. jcount is used to find where this ends.
            in_kcount;

    float   *j = new float[jcount],
            *k = new float[kcount],
            *in_j,
            *in_k;

    for(int i = 0; i < jcount; ++i) // Write bologna data...
        j[i] = (float)i;
    for(int i = 0; i < kcount; ++i)
        k[i] = (float)i;

    std::ofstream outfile("test.dat");

    outfile.write((char*)&jcount, sizeof(int)); // Good
    outfile.tellp();

    outfile.write((char*)&kcount, sizeof(int)); // Good
    outfile.tellp();

    outfile.write((char*)j, sizeof(float) * jcount); // I don't know if this works!
    outfile.tellp();

    outfile.write((char*)k, sizeof(float) * kcount); // I don't know if this works!
    outfile.tellp();

    outfile.close();


    std::ifstream in("test.dat");

    in.read((char*)&in_jcount, sizeof(int));    // == jcount == 100, good.
    in.read((char*)&in_kcount, sizeof(int));    // == kcount == 200, good.

    in_j = new float[in_jcount],
    in_k = new float[in_kcount];    // Allocate arrays the exact size of what it should be

    in.read((char*)in_j, sizeof(float) * in_jcount);    // This is where it goes bad!
    in.read((char*)in_k, sizeof(float) * in_kcount);

    float   jtest_min = j[0],   // 0.0
            jtest_max = j[jcount - 1],  // this is 99.

            ktest_min = k[0],   // 0.0
            ktest_max = k[kcount - 1],  // this is 200. Why? It should be 199!

            in_jtest_min = in_j[0], // 0.0
            in_jtest_max = in_j[in_jcount - 1], // 99

            in_ktest_min = in_k[0], // 0.0
            in_ktest_max = in_k[in_kcount - 1]; // MIN_FLOAT, should be 199. What is going on here?

    in.close();

    delete k;
    delete j;
    delete in_j;
    delete in_k;
}
4

2 に答える 2

1

同じバグがあります。バイナリ ファイルを使用して修正します。

ofstream outfile;
outfile.open ("test.dat", ios::out | ios::binary);

ifstream in;
in.open ("test.dat", ios::in | ios::binary);
于 2012-03-16T15:54:10.587 に答える
1

入力/出力ファイルを開くときにエラーをチェックしていないという事実を除いて、このコードには明らかな問題はありません (実際、実行しようとしてもエラーは表示されません)。

たとえば、「test.dat」への書き込み権限がない場合、開くことは黙って失敗し、前にたまたまファイルにあったものを読み戻します。

于 2010-12-04T03:43:35.350 に答える