proto_tool.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #include "proto_tool.h"
  2. #include <fcntl.h>
  3. #include<unistd.h>
  4. #include <google/protobuf/io/zero_copy_stream_impl.h>
  5. #include <google/protobuf/text_format.h>
  6. using google::protobuf::io::FileInputStream;
  7. using google::protobuf::io::FileOutputStream;
  8. using google::protobuf::io::ZeroCopyInputStream;
  9. using google::protobuf::io::CodedInputStream;
  10. using google::protobuf::io::ZeroCopyOutputStream;
  11. using google::protobuf::io::CodedOutputStream;
  12. using google::protobuf::Message;
  13. //读取protobuf 配置文件,转化为protobuf参数形式
  14. //input: prototxt_path :prototxt文件路径
  15. //ouput: parameter: protobuf参数,这里是消息基类,实际调用时传入对应的子类即可。
  16. bool proto_tool::read_proto_param(std::string prototxt_path, ::google::protobuf::Message& protobuf_parameter)
  17. {
  18. int fd = open(prototxt_path.c_str(), O_RDONLY);
  19. if (fd == -1) return false;
  20. FileInputStream* input = new FileInputStream(fd);
  21. bool success = google::protobuf::TextFormat::Parse(input, &protobuf_parameter);
  22. delete input;
  23. close(fd);
  24. return success;
  25. }
  26. //读取protobuf 配置文件,转化为protobuf参数形式
  27. //input: prototxt_path :prototxt文件路径
  28. //ouput: parameter: protobuf参数,这里是消息基类,实际调用时传入对应的子类即可。
  29. bool proto_tool::write_proto_param(std::string prototxt_path, ::google::protobuf::Message& protobuf_parameter)
  30. {
  31. int fd = open(prototxt_path.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
  32. if (fd == -1) {
  33. std::cout << "open false " << prototxt_path << std::endl;
  34. return false;
  35. }
  36. FileOutputStream* output = new FileOutputStream(fd);
  37. bool success = google::protobuf::TextFormat::Print(protobuf_parameter, output);
  38. delete output;
  39. close(fd);
  40. return success;
  41. }