Reputation: 955
The following code writes to file as expected
int ofd = open(filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0777);
google::protobuf::io::FileOutputStream outp(ofd);
google::protobuf::io::GzipOutputStream fout(&outp);
MyMessage msg;
ConstructMessage(&msg);
CHECK(google::protobuf::util::SerializeDelimitedToZeroCopyStream(msg, &fout));
fout.Close();
// close(ofd);
However if I uncomment the last line // close(ofd);
, I get empty file. Why is that?
Also if I skip using the Gzip wrapper, the last line causes no problem. Does this look like a bug?
Upvotes: 0
Views: 253
Reputation: 12176
You should close things in the opposite order of opening:
int ofd = open(filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0777);
google::protobuf::io::FileOutputStream outp(ofd);
google::protobuf::io::GzipOutputStream fout(&outp);
...
fout.Close();
outp.Close();
close(ofd);
With the missing outp.Close();
, some data may remain buffered in it. The destructor will eventually flush it out, but at that point the ofd
is already closed so there is nothing to write to.
Upvotes: 2