2012-05-31 3 views
7

analysieren Nach dem Codebeispiel https://developers.google.com/protocol-buffers/docs/cpptutorial zeigen sie, wie in einer Proto-Datei im Binärformat analysiert wird. mitIn Textdatei für Google Protocol Buffer

tutorial::AddressBook address_book; 

{ 
    // Read the existing address book. 
    fstream input(argv[1], ios::in | ios::binary); 
    if (!address_book.ParseFromIstream(&input)) { 
    cerr << "Failed to parse address book." << endl; 
    return -1; 
    } 
} 

Ich versuchte, die ios::binary für meine Eingabedatei zu entfernen, die im Textformat ist, aber das immer noch nicht in der Datei zu lesen. Was muss ich tun, um eine Proto-Datei im Textformat einzulesen?

Antwort

3

Was muss ich tun, um eine Proto-Datei im Textformat einzulesen?

Verwenden Sie TextFormat::Parse. Ich weiß nicht genug C++, um Ihnen vollen Beispielcode zu geben, aber TextFormat ist, wo Sie suchen sollten.

12

In Ordnung, ich habe das herausgefunden. in einem Text Proto-Datei in ein Objekt ....

#include <iostream> 
#include <fcntl.h> 
#include <fstream> 
#include <google/protobuf/text_format.h> 
#include <google/protobuf/io/zero_copy_stream_impl.h> 

#include "YourProtoFile.pb.h" 

using namespace std; 

int main(int argc, char* argv[]) 
{ 

    // Verify that the version of the library that we linked against is 
    // compatible with the version of the headers we compiled against. 
    GOOGLE_PROTOBUF_VERIFY_VERSION; 

    Tasking *tasking = new Tasking(); //My protobuf object 

    bool retValue = false; 

    int fileDescriptor = open(argv[1], O_RDONLY); 

    if(fileDescriptor < 0) 
    { 
    std::cerr << " Error opening the file " << std::endl; 
    return false; 
    } 

    google::protobuf::io::FileInputStream fileInput(fileDescriptor); 
    fileInput.SetCloseOnDelete(true); 

    if (!google::protobuf::TextFormat::Parse(&fileInput, tasking)) 
    { 
    cerr << std::endl << "Failed to parse file!" << endl; 
    return -1; 
    } 
    else 
    { 
    retValue = true; 
    cerr << "Read Input File - " << argv[1] << endl; 
    } 

    cerr << "Id -" << tasking->taskid() << endl; 
} 

Mein Programm dauert in der Eingabedatei für die Proto Buff als erste Parameter zu lesen, wenn ich es am Terminal auszuführen. Zum Beispiel ./myProg inputFile.txt

Hoffnung hilft dies jemand mit der gleichen Frage

0

Nur das Wesentliche zusammenfassen:

#include <google/protobuf/text_format.h> 
#include <google/protobuf/io/zero_copy_stream_impl.h> 
#include <fcntl.h> 
using namespace google::protobuf; 

(...)

MyMessage parsed; 
int fd = open(textFileName, O_RDONLY); 
io::FileInputStream fstream(fd); 
TextFormat::Parse(&fstream, &parsed); 

Karo mit protobuf-3.0.0-beta-1 auf g++ 4.9.2 auf Linux.