2012-05-31 12 views
7

De acuerdo con el código de ejemplo https://developers.google.com/protocol-buffers/docs/cpptutorial, muestran cómo analizar en un archivo proto que está en formato binario. utilizandoAnalizar en archivo de texto para el Buffer de Protocolo de Google

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

traté de quitar la ios::binary para mi archivo de entrada que está en formato de texto, pero que todavía falla en la lectura en el archivo. ¿Qué debo hacer para leer en un archivo proto en formato de texto?

Respuesta

3

¿Qué debo hacer para leer en un archivo proto en formato de texto?

Use TextFormat::Parse. No sé lo suficiente de C++ para darle un código de muestra completo, pero TextFormat es donde debería estar buscando.

12

Bien, entendí esto. Para leer en un archivo de texto proto en un objeto ....

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

Mi programa toma en el archivo de entrada para el aficionado proto como primer parámetro cuando lo ejecuto en la terminal. Por ejemplo ./myProg inputFile.txt

Esperamos que esto ayude a nadie con la misma pregunta

0

Sólo para resumir lo esencial:

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

comprobado con protobuf-3.0.0-beta-1 en el g++ 4.9.2 Linux.

Cuestiones relacionadas