I can successfully serialise other fields to ASCII using google::protobuf::TextFormat::Print
, however my enums don't show up. What am I doing wrong?
Code as follows:
main.cpp
#include <iostream>
#include <filesystem>
#include <fcntl.h>
#include <unistd.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/text_format.h>
#include "example.pb.h"
bool pb_SaveToFile( const std::filesystem::path File,
const google::protobuf::Message &Message )
{
int fd = open ( File.string ( ).c_str ( ), O_WRONLY | O_CREAT | O_TRUNC, 0666 );
if ( fd == - 1 )
{
return false;
}
google::protobuf::io::FileOutputStream * output =
new google::protobuf::io::FileOutputStream ( fd );
bool success =
google::protobuf::TextFormat::Print ( Message, output );
delete output;
close ( fd );
return success;
}
int main(int argc, char *argv[])
{
std::filesystem::path fullPath = "saved.prototxt";
pbtest::PbTestMessage tm;
// Timestamp
auto ts = tm.mutable_timestamptest();
ts->set_seconds(time(NULL));
ts->set_nanos(0);
// Enum
tm.set_enumtest(::pbtest::enumTestValues::ENUM_ZERO);
// String
tm.set_stringtest("string test!");
// Save it
pb_SaveToFile(fullPath, tm);
std::cout << "Done!" << std::endl;
return 0;
}
example.proto
syntax = "proto3";
import "google/protobuf/timestamp.proto";
package pbtest;
enum enumTestValues {
ENUM_ZERO = 0;
ENUM_ONE = 1;
}
message PbTestMessage {
google.protobuf.Timestamp timestampTest = 1;
enumTestValues enumTest = 2;
string stringTest = 3;
}
CMakeLists.txt
cmake_minimum_required(VERSION 2.8.9)
project (protobuf-example)
find_package(Protobuf REQUIRED)
include_directories(${Protobuf_INCLUDE_DIRS})
include_directories(${CMAKE_CURRENT_BINARY_DIR})
protobuf_generate_cpp(PROTO_SRCS PROTO_HDRS example.proto)
add_executable(protobuf-example main.cpp ${PROTO_SRCS} ${PROTO_HDRS})
target_link_libraries(protobuf-example ${Protobuf_LIBRARIES})
target_compile_features(protobuf-example PRIVATE cxx_std_17)
If I run this, the output saved to saved.prototxt
is as follows:
timestampTest {
seconds: 1673886921
}
stringTest: "string test!"
How do I get my enum to save to my file?