如何将文本格式的protobuf消息正确写入文件

时间:2018-10-23 12:59:05

标签: c++ protocol-buffers

我的问题是如何正确将文本格式的protobuf消息写入文件。在下面的程序中,我创建一个NetParameter对象,它是一条消息 caffe.proto的消息字段中的字段。

当我呼叫print()PrintToString()时,它们返回失败。

我可以使用printf("%s", data.c_str());在控制台上打印消息,但是否注意到已写入文件?

#include <fcntl.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/text_format.h>
#include <stdint.h>
#include <algorithm>
#include <fstream> // NOLINT(readability/streams)
#include <string>
#include <vector>
#include <string>
#include "caffe.pb.h"
#include <iostream>
#include <caffe/caffe.hpp>

using namespace std;
using google::protobuf::Message;
using google::protobuf::io::CodedInputStream;
using google::protobuf::io::CodedOutputStream;
using google::protobuf::io::FileInputStream;
using google::protobuf::io::FileOutputStream;
using google::protobuf::io::ZeroCopyInputStream;
using google::protobuf::io::ZeroCopyOutputStream;
using google::protobuf::TextFormat;


int main()
{
    caffe::NetParameter param;
    const char *filename = "./test.prototxt";

    int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (fd == -1)
        cout << "File not found: " << filename;

    google::protobuf::io::FileOutputStream* output = new google::protobuf::io::FileOutputStream(fd);

    param.set_name("AlexNet");
    param.add_input_dim(0);
    param.add_input_dim(1);
    param.add_input_dim(2);
    param.set_input_dim(0, 3);
    param.set_input_dim(1, 3);
    param.set_input_dim(2, 3);

    std::string data;
    bool success = google::protobuf::TextFormat::PrintToString(param, &data);
    std::cout << "bool is " << success << std::endl;
    printf("%s", data.c_str());

    bool success1 = google::protobuf::TextFormat::Print(param, output);
    std::cout << "bool is " << success << std::endl;



    close(fd);
    return 0;
}

0 个答案:

没有答案