我正在为我的硕士论文编写一个工具,它需要从文件中读取 protobuf 数据流。到目前为止,我只在 Mac OS 上工作,一切都很好,但现在我也尝试在 Windows 上运行该工具。
遗憾的是,在 Windows 上我无法从单个流中读取多个连续消息。我试图缩小问题范围,并找到了以下重现问题的小程序。
#include "tokens.pb.h"
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <fstream>
int main(int argc, char* argv[])
{
std::fstream tokenFile(argv[1], std::ios_base::in);
if(!tokenFile.is_open())
return -1;
google::protobuf::io::IstreamInputStream iis(&tokenFile);
google::protobuf::io::CodedInputStream cis(&iis);
while(true){
google::protobuf::io::CodedInputStream::Limit l;
unsigned int msgSize;
if(!cis.ReadVarint32(&msgSize))
return 0; // probably reached eof
l = cis.PushLimit(msgSize);
tokenio::Union msg;
if(!msg.ParseFromCodedStream(&cis))
return -2; // couldn't read msg
if(cis.BytesUntilLimit() > 0)
return -3; // msg was not read completely
cis.PopLimit(l);
if(!msg.has_string() &&
!msg.has_file() &&
!msg.has_token() &&
!msg.has_type())
return -4; // msg contains no data
}
return 0;
}
在 Mac OS 上,它运行良好,并在按照我的预期读取整个文件后返回 0。
在 Windows 上,第一条消息的读取没有问题。对于第二条消息ParseFromCodedInputStream
仍然返回true,但不读取任何数据。这会导致 BytesUntilLimit
值大于 0,并且返回值为 -3。当然,该消息也不包含任何可用的数据。即使文件尚未完全读取,从 cis
进行的任何进一步读取也将失败,就好像已到达流末尾一样。
我还尝试使用带有文件描述符的FileInputStream
进行输入,得到相同的结果。删除 Push/PopLimit
并使用具有显式消息大小的 ReadString
调用读取数据,然后从该字符串进行解析也没有帮助。
使用了以下 protobuf 文件。
package tokenio;
message TokenType {
required uint32 id = 1;
required string name = 2;
}
message StringInstance {
required string value = 1;
optional uint64 id = 2;
}
message BeginOfFile {
required uint64 name = 1;
optional uint64 type = 2;
}
message Token {
required uint32 type = 1;
required uint32 offset = 2;
optional uint32 line = 3;
optional uint32 column = 4;
optional uint64 value = 5;
}
message Union {
optional TokenType type = 1;
optional StringInstance string = 2;
optional BeginOfFile file = 3;
optional Token token = 4;
}
和this is a sample input file .
输入文件似乎没问题。至少它可以被 protobuf 编辑器(在 Windows 和 Mac OS 上)以及 Mac OS 上的 C++ 实现读取。
代码已经过测试:
- 在 Mac OS 10.8.4 上运行,使用 Xcode 4.6.3 和 protobuf 2.5.0 编译
- 无法在 Windows 8 64 位上运行,使用 Visual Studio 2012 Ultimate 和 protobuf 2.5.0 编译
我做错了什么?
最佳答案
使其成为std::fstream tokenFile(argv[1], std::ios_base::in | std::ios_base::binary);
。默认为文本模式;在 Mac 和其他类 Unix 系统上这并不重要,但在文本模式下的 Windows 上,您可以将 CRLF 序列转换为 LF,并将 ^Z(又名“\x1A”)字符视为文件结束指示符。这些字符可能会巧合地出现在二进制流中,并引起麻烦。
关于c++ - 从 Windows 上的文件中读取多个分隔的 protobuf 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18123167/