1

私の質問は、バイナリ ファイルの I/O に関するものです。次のコードが実行されるとします。

#include <iostream>
#inclide <fstream>

int main(){
    fstream out;
    out.open("binfile.bin",ios::binary|ios::out);
    if(!out.good()){
        cout<<"ain't good"<<endl;
        return EXIT_FAILURE;
    }
    out.seekp(3);
    out<<char(74);
    out.seekp(7);
    out<<char(73);
    out.close();
}

期待どおり、 binfile.bin には が含まれ00 00 00 4A 00 00 00 49ています。何を出力するかを指定しない場合、ファイルに配置されるデフォルト値を何らかの方法で変更できますか? のようなものに置き換え0030、binfile.bin に が含まれる ようにしたいのですが30 30 30 4A 30 30 30 49、それは可能ですか? もちろん、最後にファイルをループしてすべて00の s を30s に置き換えることはできますが、それは避けたいと思います。

4

2 に答える 2

0

You could write a wrapper for seekp and use that. Pseudocode:

my_seekp(fstream& f, int pos)
{
    seek to end
    endpos = position at end
    if (pos > endpos)
    {
        int n = endpos - pos;
        for (int i = 0; i < n; ++i)
            f.put(char(30));
    }
    else
        seek to pos
}
于 2011-06-07T19:11:15.747 に答える
0

<< を使用して値を検索して char として書き込む代わりに、char buf[4] 配列を割り当てて、すべての要素に必要な「塗りつぶし」値を設定し、最初/最後の要素を必要な値で更新して、 out.write(buf, 4)? を呼び出す

于 2011-06-08T19:10:17.343 に答える