首页 > 解决方案 > C++:读取二进制文件并提取值

问题描述

我需要一个启动来帮助我在 C++ 中读取我的二进制文件并使用提取的值。我基本上知道文件的结构和数据的种类。它包含一个固定的标头,然后是包含多个我想以双精度类型值存储的数据的事件。

# The data format is the following one
#;    It consists of a common header containing (4 + N_boards) 32-bit words:
#        
#;        Word 1 = Version
#;        Word 2 = Time base
#;        Word 3 = Number of events registered
#;        Word 4 = Number of boards (N_boards)
#;        Words 4+1 to 4+N_boards = Info about each board (I don't need to read this so I have to skip that)
#;        
#;    Then it follows the list of events, stored using 4 x 32 bits. I need to store this into double values.
#;    
#;        Word 1 --> Crate                ( 4 bits: 31-28)
#;                   Board                ( 6 bits: 27-22)
#;                   Channel              ( 6 bits: 21-16)
#;                   Timestamp bits 47-32 (16 bits: 15-0)
#;                   
#;        Word 2 --> Timestamp bits 31-0  (32 bits: 31-0) 
#;        
#;        Word 3  --> X position (5 bits: 20-16)
#;                    Y position (8 bits: 7-0)       
#;
#;        Word 4 --> A+B (16 bits: 31-16)
#;                   A   (16 bits: 15-0)

我成功地正确读取了标题:

ifstream input (BufferPath[i].c_str(), ios::binary);

input.seekg(0, ios::end);
end = input.tellg();
input.seekg(0, ios::beg);

// Read the 4 fixed elements of the header.
uint32_t nbEvents = 0;
uint32_t nbBoards = 0;
uint32_t timeBase = 0;
uint32_t version = 0;

input.read(reinterpret_cast<char *>(&version), sizeof(int32_t));
input.read(reinterpret_cast<char *>(&timeBase), sizeof(int32_t));
input.read(reinterpret_cast<char *>(&nbEvents), sizeof(int32_t));
input.read(reinterpret_cast<char *>(&nbBoards), sizeof(int32_t));

但是,我很难跳过标题的其余部分,并从我的事件中读取数据并将其隔离为单独的值。我考虑过使用缓冲区来存储所有内容,但是如何拆分存储的值?

std::vector<unsigned char> buffer(std::istreambuf_iterator<char>(input), {});

正如你所看到的,我对处理二进制文件感到困惑,所以任何帮助都将不胜感激。

提前非常感谢:)!

标签: c++filebinary

解决方案


推荐阅读