Doing serialization using streams C++

前端 未结 2 1020
余生分开走
余生分开走 2020-12-22 06:59

I implemented some serialization / deserialization using C++ after some help on this forum. The file seems to be written correctly but when I read it, new lines are ignored

相关标签:
2条回答
  • 2020-12-22 07:13

    Today you almost never need to implement your own low-level serialization.

    Try JSON, BSON, Protocol Buffers, MessagePack or XML.

    There are quite a lot of libraries, that will do it better than "roll-your-own"...

    You intended to write a binary serialization, but you insert EOL ('\n') characters. That's not a good choice of dividing a binary stream into tokens.

    0 讨论(0)
  • 2020-12-22 07:27

    The reason for the error message is clear: you input from binary_file2 until an input fails (generally because there is no more data, because you've reached end of file), then you say to output "error parsing of input file" if any input has failed.

    As for the loss of new lines, you read product_name_ and other_data_ using std::getline, which extracts throught the final newline, but does not insert it into the string it is reading. In the loop where you're outputting to cout, you need an endl after each field.

    With regards to your question: the main advantage of doing it the way you are, instead of using write(record, sizeof(Product)), etc., is that it works. Generally speaking, you cannot write binary images of what you have in memory, and expect to be able to reread them correctly. If you want to be able to seek (which can be useful), you'll have to define a fixed length representation in your output file. (This can be done by forcing each output field to have a fixed length, using std::setw.)

    0 讨论(0)
提交回复
热议问题