gpt4 book ai didi

c++ - Protocol Buffer ;将数据保存到磁盘并加载回问题

转载 作者:可可西里 更新时间:2023-11-01 18:33:26 29 4
gpt4 key购买 nike

我在将 Protobuf 数据存储到磁盘时遇到问题。我的应用程序使用 Protocol Buffer 通过套接字传输数据(工作正常),但是当我尝试将数据存储到磁盘时它失败了。实际上,保存数据报告没有问题,但我似乎无法再次正确加载它们。任何提示将不胜感激。

void writeToDisk(DataList & dList)
{
// open streams
int fd = open("serializedMessage.pb", O_WRONLY | O_CREAT);
google::protobuf::io::ZeroCopyOutputStream* fileOutput = new google::protobuf::io::FileOutputStream(fd);
google::protobuf::io::CodedOutputStream* codedOutput = new google::protobuf::io::CodedOutputStream(fileOutput);

// save data
codedOutput->WriteLittleEndian32(PROTOBUF_MESSAGE_ID_NUMBER); // store with message id
codedOutput->WriteLittleEndian32(dList.ByteSize()); // the size of the data i will serialize
dList.SerializeToCodedStream(codedOutput); // serialize the data

// close streams
delete codedOutput;
delete fileOutput;

close(fd);
}

我已经验证了这个函数中的数据,dList 包含我期望的数据。流报告没有发生错误,并且向磁盘写入了合理数量的字节。 (文件大小也合理)但是当我尝试读回数据时,它不起作用。此外,真正奇怪的是,如果我向该文件附加更多数据,我可以读取第一条消息(但不能读取末尾的消息)。

void readDataFromFile()
{
// open streams
int fd = open("serializedMessage.pb", O_RDONLY);
google::protobuf::io::ZeroCopyInputStream* fileinput = new google::protobuf::io::FileInputStream(fd);
google::protobuf::io::CodedInputStream* codedinput = new google::protobuf::io::CodedInputStream(fileinput);

// read back
uint32_t sizeToRead = 0, magicNumber = 0;
string parsedStr = "";

codedinput->ReadLittleEndian32(&magicNumber); // the message id-number i expect
codedinput->ReadLittleEndian32(&sizeToRead); // the reported data size, also what i expect
codedinput->ReadString(&parsedstr, sizeToRead)) // the size() of 'parsedstr' is much less than it should (sizeToRead)

DataList dl = DataList();

if (dl.ParseFromString(parsedstr)) // fails
{
// work with data if all okay
}

// close streams
delete codedinput;
delete fileinput;
close(fd);
}

显然我在这里省略了一些代码以简化一切。作为旁注,我还尝试将消息序列化为字符串并通过 CodedOutputStream 保存该字符串。这也不起作用。不过,我已经验证了该字符串的内容,所以我猜罪魁祸首一定是流函数。

这是一个 Windows 环境,带有 Protocol Buffer 和 Qt 的 C++。

感谢您的宝贵时间!

最佳答案

我通过从文件描述符切换到 fstream,并将 FileCopyStream 切换到 OstreamOutputStream 解决了这个问题。

虽然我见过使用前者的示例,但它对我不起作用。

我在 google coded_stream header 中找到了一个很好的代码示例。 link #1

此外,由于我需要使用 Protocol Buffer 将多条消息序列化到同一个文件中,因此此链接很有启发性。 link #2

出于某种原因,在我实际解构流对象之前,输出文件并不“完整”。

关于c++ - Protocol Buffer ;将数据保存到磁盘并加载回问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12581435/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com