このフォーラムの助けを借りて、C++ を使用していくつかのシリアライゼーション/デシリアライゼーションを実装しました。ファイルは正しく書かれているようですが、私がそれを読むと、次のように新しい行は無視され、いくつかのデータが互いに沿って出力されます:
これは私のコードです。フィードバック、ヘルプ、それを改善する方法、大歓迎です:
#include "stdafx.h"
#include <iostream>
#include <string>
#include <fstream> // std::ifstream
using namespace std;
struct Product
{
double price_;
double product_index_;
std::string product_name_;
std::string other_data_;
friend std::ostream& operator<<(std::ostream& os, const Product& p)
{
return os << p.price_ << '\n'
<< p.product_index_ << '\n'
<< p.product_name_ << '\n'
<< p.other_data_ << '\n';
}
friend std::istream& operator>>(std::istream& is, Product& p)
{
is >> p.price_ >> p.product_index_;
is.ignore(std::numeric_limits<streamsize>::max(), '\n');
getline(is,p.product_name_);
getline(is,p.other_data_);
return is;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Product s1,s2,s3,s4;
s1.price_ = 100;
s1.product_index_ = 0;
s1.product_name_= "flex";
s1.other_data_ = "dat001";
s2.price_ = 200;
s2.product_index_ = 1;
s2.product_name_= "brr";
s2.other_data_ = "dat002";
s3.price_ = 300;
s3.product_index_ = 2;
s3.product_name_= "megatex";
s3.other_data_ = "dat003";
// write
fstream file1("c:\\test.dat",ios::out|ios::binary|ios::app);
file1_file << s1 << s2 << s3;
file1_file.close();
// read
ifstream file2("c:\\test.dat");
Product p;
while (file2 >> p)
{
cout<<p.price_<<endl;
cout<<p.product_index_<<endl;
cout<<p.product_name_;
cout<<p.other_data_;
}
if (!file2.good())
std::cerr << "error during parsing of input file\n";
else
std::cerr << "error opening input file\n";
return 0;
}
また、最後にエラーが発生するのはなぜですか?
PS。次のような読み取りwrite(record, sizeof(Product))
と書き込みを使用するアプローチと比較して、上記のアプローチの利点は何ですか。ヒント: POD 関連の制限と移植性について聞いたことがありますseek(record_size * n, SEEK_SET)
read(record, sizeof(Product))