岚天逸见

取得std::ifstream对象的文件描述符

使用C++标准库无法取得std::ifstream对象的文件描述符,但GNU libstdc++库可以取得:

#include <fstream>
#include <iostream>
#include <ext/stdio_filebuf.h>

int main() {
    std::ifstream ifs("test.txt");
    if (!ifs) {
        std::cerr << "Failed to open file\n";
        return 1;
    }

    __gnu_cxx::stdio_filebuf<char>* filebuf =
        static_cast<__gnu_cxx::stdio_filebuf<char>*>(ifs.rdbuf());

    if (!filebuf) {
        std::cerr << "Failed to get filebuf\n";
        return 1;
    }

    int fd = filebuf->fd();

    std::cout << "File descriptor: " << fd << '\n';

    return 0;
}
  • 参考资料:
https://opensource.apple.com/source/gcc/gcc-1640/libstdc++-v3/include/ext/stdio_filebuf.h.auto.html
https://gcc.gnu.org/onlinedocs/gcc-4.6.2/libstdc++/api/a00069.html

posted on   岚天逸见  阅读(45)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
历史上的今天:
2021-09-05 编译 thrift-0.14.2 的 C++ 版本
2019-09-05 进一步理解指针:一维数组和二维数组转换
2019-09-05 进一步理解指针2:双指针、指针数组和数组指针
2019-09-05 彻底理解C++指针
2019-09-05 如何安全地使用redis的pop命令

导航

统计信息

点击右上角即可分享
微信分享提示