2012-05-31 17 views
7

Zgodnie z przykładowym kodem https://developers.google.com/protocol-buffers/docs/cpptutorial, pokazują sposób analizowania w pliku proto w formacie binarnym. stosującAnaliza pliku tekstowego dla bufora protokołu 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; 
    } 
} 

Próbowałem usunięcie ios::binary dla mojego pliku wejściowego, który jest w formacie tekstowym, ale to nadal nie czytając w pliku. Co muszę zrobić, aby przeczytać w pliku proto w formacie tekstowym?

Odpowiedz

3

Co należy zrobić, aby przeczytać w pliku proto w formacie tekstowym?

Użyj TextFormat::Parse. Nie wiem wystarczająco dużo C++, aby podać pełny przykładowy kod, ale TextFormat to miejsce, w którym powinieneś szukać.

12

Dobra, mam to ustalone. Aby przeczytać w pliku tekstowym proto do obiektu ....

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

Mój program trwa w pliku wejściowym dla buff proto jako pierwszy parametr kiedy go wykonać w terminalu. Na przykład ./myProg inputFile.txt

Nadzieja to pomaga ktoś z tym samym pytaniem

0

Wystarczy, aby podsumować Essentials:

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

sprawdzane protobuf-3.0.0-beta-1 na g++ 4.9.2 na Linux.

Powiązane problemy