2012-05-31 9 views
7

In base al codice di esempio https://developers.google.com/protocol-buffers/docs/cpptutorial, essi mostrano come analizzare in un file proto che è in formato binario. utilizzandoAnalizza file di testo per 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; 
    } 
} 

Ho provato a rimuovere il ios::binary per il mio file di input che è in formato testo, ma che non riesce ancora a leggere nel file. Cosa devo fare per leggere un proto file in formato testo?

risposta

3

Cosa devo fare per leggere un proto file in formato testo?

Utilizzare TextFormat::Parse. Non conosco abbastanza C++ per darti un codice di esempio completo, ma TextFormat è dove dovresti cercare.

12

OK, ho capito. Per leggere in un file di proto testo in un oggetto ....

#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; 
} 

mio programma prende nel file di input per il buff proto come primo parametro quando eseguo al terminal. Per esempio ./myProg inputFile.txt

Spero che questo aiuti chiunque con la stessa domanda

0

Giusto per riassumere gli elementi essenziali:

#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); 

controllato con protobuf-3.0.0-beta-1 su g++ 4.9.2 su Linux.

Problemi correlati