从std::fstream获得文件描述符

核心:

  auto helper = [](std::filebuf& fb) -> int {
    class Helper : public std::filebuf {
    public:
      int handle() { return _M_file.fd(); }
    };

    return static_cast<Helper&>(fb).handle();
  };

示例:

#include <iostream>
#include <fstream>
#include <string>
#include <unistd.h>

int main()
{
  std::string str("Hello World");

  std::ofstream fs("path",
    std::ofstream::binary | std::ofstream::out | std::ofstream::in);

  if (!fs.is_open())
    fs.open("path",
      std::ofstream::binary | std::ofstream::out);

  auto helper = [](std::filebuf& fb) -> int {
    class Helper : public std::filebuf {
    public:
      int handle() { return _M_file.fd(); }
    };

    return static_cast<Helper&>(fb).handle();
  };

  int fd = helper(*fs.rdbuf());

  fs.seekp(0, fs.beg);
  fs.write(str.data(), str.length());
  fsync(fd);
  fs.close();

  return 0;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容