バイナリファイルへの書き込みと読み戻しに非常に苦労しています。私は基本的にこの形式のレコードを書いています
1234|ABCD|efgh|IJKL|ABC
このレコードを書き込む前に、このレコード全体の長さを書き込みます (次に、次のようにusing string.size())
使用してバイナリ ファイルにレコードを書き込みます。ofstream
int サイズ;
ofstream studentfile;
studentfile.open( filename.c_str(),ios::out|ios::binary );
studentfile.write((char*)&size,sizeof(int));
studentfile.write(data.c_str(),(data.size()*(sizeof(char))));
cout << "Added " << data << " to " << filename << endl;
studentfile.close();
そして、私はこのデータを別の場所で読みました
ifstream ifile11;
int x;
std::string y;
ifile11.open("student.db", ios::in |ios::binary);
ifile11.read((char*)&x,sizeof(int));
ifile11.read((char*)&y,x);
cout << "X " << x << " Y " << y << endl;
まず、レコードの長さを変数 x に読み込み、次にレコードを文字列 y に読み込みます。問題は、出力が x を '0' として示し、'y' が空であることです。
私はこれを理解することができません。この問題を調べて洞察を提供できる人に感謝します。
ありがとうございました