蓝天

取得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 2023-09-05 14:18  #蓝天  阅读(37)  评论(0编辑  收藏  举报

导航