2017-03-16 1 views
2

Cppを使ってバイナリファイルを読んでいますが、そのタイプはMsgPackです。 私はMsgPackに精通していないので、私はバイナリファイルの拳を読んでMsgPackをプッシュしようとしています。それは動作しません。それはちょうど最初の番号を何度も何度も取得します。誰も助けることができますか?どうもありがとう。MsgPackをC++で使ってバイナリファイルを読む

#include <bits/stdc++.h> 
#include <msgpack.hpp> 
using namespace std; 

int main() 
{ 
    std::ifstream ifs("input.txt", std::ifstream::in); 
    std::stringstream buffer; 
    buffer << ifs.rdbuf(); 
    msgpack::unpacked upd; 
    msgpack::unpack(upd, buffer.str().data(), buffer.str().size()); 
    std::cout << upd.get() << std::endl; 
    return 0; 
} 

これは最初の数字「3」を得ることができます。

私は数を得ることを望んだ:

3 
[3 6 7 5 3 5] 
[6 2 9 1 2 7] 
[0 9 3 6 0 6] 

そしてhereは、入力バイナリファイルです。

答えて

0

msgpack::unpack()は、最初のMessagePackフォーマットデータをアンパックします。 3は、次の配列の数を意味します。

この場合、offsetが便利です。 https://github.com/msgpack/msgpack-c/wiki/v2_0_cpp_unpacker#client-controls-a-buffer

ここでは、最初のMessagePackデータ3をカウンタとして読み取るコードを示します。その後、各アレイを開梱するために3回msgpack::unpack()と呼んでください。 そのプロセス中に、変数offsetが更新されます。

#include <iostream> 
#include <fstream> 
#include <msgpack.hpp> 

int main() 
{ 
    std::ifstream ifs("input.txt"); 
    std::string buffer((std::istreambuf_iterator<char>(ifs)), 
         std::istreambuf_iterator<char>()); 
    msgpack::unpacked upd; 
    std::size_t offset = 0; 
    msgpack::unpack(upd, buffer.data(), buffer.size(), offset); 
    std::size_t count = upd.get().as<std::size_t>(); 
    std::cout << count << std::endl; 
    for (std::size_t i = 0; i != count; ++i) { 
     msgpack::unpack(upd, buffer.data(), buffer.size(), offset); 
     std::cout << upd.get() << std::endl; 
    } 

}

私はこれがあなたの元のコードに基づいたアプローチであると信じています。

+0

あなたの解答に基づいて、最初の数字は次の配列の数です。それが間違っていて、@Gavin Leeが4つの独立メッセージを解析したければどうなりますか?少なくとも、あなたのforループで 'offset'がまだ' buffer.size() 'よりも小さいかどうかを調べることができます。 – JustRufus

0

私はここで問題を考える:buffer.str().size()あなたが

buffer.str().length() 

かはstrlen(buffer.str()データ()c_str()。。)を試すことができます。

+0

std :: string :: sizeとstd :: string :: lengthはどちらも '同義語'です。 http://en.cppreference.com/w/cpp/string/basic_string/size – JustRufus

0

あなたのコードは、1つのmsgpackメッセージ(最初のメッセージは3つです)をアンパックしますが、実際にはファイルには4つのメッセージが含まれています。したがって、msgpack::unpackerクラスを使用すると、すべてのメッセージを1つずつアンパックすることができます。

int main() 
{ 
    std::ifstream ifs("input.txt", std::ifstream::in); 
    std::string buffer((std::istreambuf_iterator<char>(ifs)), 
         std::istreambuf_iterator<char>()); 

    msgpack::unpacker pac; 
    pac.reserve_buffer(buffer.size()); 
    std::copy(buffer.begin(), buffer.end(), pac.buffer()); 
    pac.buffer_consumed(buffer.size()); 

    msgpack::object_handle oh; 
    while (pac.next(oh)) { 
     msgpack::object msg = oh.get(); 
     std::cout << msg << std::endl; 
    } 
    return 0; 
} 

P.S. thisを読んで、#include <bits/stdc++.h>の使用を中止してください。

関連する問題