在这个论坛上获得一些帮助后,我使用 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))
和seek(record_size * n, SEEK_SET)
,read(record, sizeof(Product))
(读取第 n 个产品);提示:我听说过 POD 相关的限制和可移植性