Home > front end >  google::protobuf::io::GzipOutputStream does not write anything if the file handle is closed at the e
google::protobuf::io::GzipOutputStream does not write anything if the file handle is closed at the e

Time:02-28

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?

CodePudding user response:

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.

  • Related