1

Since I have to work with files in binary a lot, I would like to have a more abstract way to do that, I have have to perform the same loop over and over:

  • write an header
  • write different kind of chunks ( with different set of values ) in a given order
  • write an optional closing header

Now I would like to break down this problem in small building blocks, imagine if I can write something like what the DTD is for the XML, a definition of what can possibly be in after a given chunk or inside a given semantic, so I can think about my files in terms of building blocks instead of hex values or something like that, also the code will be much more "idiomatic" and less cryptic.

In the end, there something in the language that can help me with binary files from this prospective ?

4

1 回答 1

3

我不确定 C++11 的特定功能,但对于一般的 C++,流使文件 I/O 更易于使用。您可以重载流插入 (<<) 和流提取 (>>) 运算符来实现您的目标。如果您对运算符重载不是很熟悉,请参阅本网站的第 9 章,它很好地解释了它,并附有大量示例。这是在流的上下文中重载 << 和 >> 运算符的特定页面

请允许我说明我的意思。假设我们定义了几个类:

  1. BinaryFileStream - 代表您尝试写入和(可能)读取的文件。
  2. BinaryFileStreamHeader - 代表文件头。
  3. BinaryFileStreamChunk - 代表一个块。
  4. BinaryFileStreamClosingHeader - 表示关闭标头。

然后,您可以重载 BinaryFileStream 中的流插入和提取运算符来写入和读取文件(或任何其他 istream 或 ostream)。

...
#include <iostream> // I/O stream definitions, you can specify your overloads for
                    // ifstream and ofstream, but doing so for istream and ostream is
                    // more general

#include <vector>   // For holding the chunks

class BinaryFileStream
{
public:
...
    // Write binary stream
    friend const std::ostream& operator<<( std::ostream& os, const BinaryFileStream& bfs )
    {
         // Write header
         os << bfs.mHeader;

         // write chunks
         std::vector<BinaryFileStreamChunk>::iterator it;
         for( it = bfs.mChunks.begin(); it != bfs.mChunks.end(); ++it )
         {
             os << (*it);
         }

         // Write Closing Header
         os << bfs.mClosingHeader;

         return os;
    }
...
private:
    BinaryFileStreamHeader             mHeader;
    std::vector<BinaryFileStreamChunk> mChunks;
    BinaryFileStreamClosingHeader      mClosingHeader;
};    

然后,您必须做的就是为您的 BinaryFileStreamHeader、BinaryFileStreamChunk 和 BinaryFileStreamClosingHeader 类提供运算符重载,将它们的数据转换为适当的二进制表示。

您可以以类似的方式重载流提取运算符 (>>),尽管解析可能需要一些额外的工作。

希望这可以帮助。

于 2013-07-15T04:18:53.537 回答