3

コードを見てください。私は初心者で、C++ でバッファを作成するのはこれが初めてです。C++ でバッファを作成して、そのバッファに古い内容を読み込んだ後、削除する部分を無視して古いデータを切り捨て、バッファから内容を保存し直した後、新しいファイルを作成する方法は?

int main() {
    Admin item; // Admin is a class
    ios::pos_type pos;    
    int productId;
    char *ch; // pointer to create buffer
    int length;

    cout << "Enter Product Id of item to delete: ";

    cin >> productId;

    ifstream readFile("Stock.dat", ios::binary | ios:: in | ios::out);

    while (readFile) {
        readFile.read(reinterpret_cast<char*>(&item), sizeof(Admin));

        if (item.getStatus() == productId) {            
            pos = readFile.tellg() - sizeof(Admin);
            break;
        }
    }

    readFile.close();

    ifstream readNewFile("Stock.dat", ios::binary | ios:: in | ios::out);

    readNewFile.seekg(0, ios::end);

    length = readNewFile.tellg();

    ch = new char[length]; // is this how buffer is created?if no, please correct it. 

    readNewFile.seekg(0, ios::beg);

    while (readNewFile) {
        if (readNewFile.tellg() == pos)
            readNewFile.ignore(sizeof(Admin));
        readNewFile.read((ch), sizeof(Admin)); // is this how contents are read into buffer from file stream;

        if (readNewFile.eof())
            readNewFile.close();
    }

    ofstream outFile("Stock.dat", ios::trunc | ios::app);

    outFile.write(ch, sizeof(Admin)); // I am doubtful in this part also

}
4

2 に答える 2

4

C++ では、次のようにメモリを割り当ててバッファを作成します。

char* buffer = new char[length];

コードの問題は、の()代わりに使用したことです[]

これらのバッファのメモリを解放したい場合は、次のdelete[]演算子を使用します。

delete[] buffer;

また、ファイルから正しく読み取っていますが、期待どおりではありません。これは有効な構文ですが、問題は、バッファ内のデータを上書きしていることです。

あなたはおそらく次のように読んでいるはずです: ( whereindexはループの前にint初期化されています)0while

readNewFile.read(&ch[index], sizeof(Admin));
index = index + sizeof(Admin);

コメントのユーザーが示唆したようにstd::vector<char>、 a と同じくらい高速でchar*、指定されたサイズを必要としないため、 here を使用することもできます:)

于 2013-03-23T19:13:02.190 に答える
0

を行いますch = new char[length]。また、http://www.cplusplus.com/doc/tutorial/dynamic/も良い出発点です。

余談ですが、あなたが初心者であることは理解していますので、がっかりさせたくはありませんが、投稿する前に簡単に答えられる質問について調査を行っていただければ幸いです。

于 2013-03-23T19:17:21.113 に答える