Linux下C++获取文件流的文件描述符fd

如题

先上代码:

核心代码


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

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

实例,下面通过重定向到标准输出,来将输入打印到屏幕
//注意,因为用的是ofstream,其缓冲区规则是全缓冲,如果你想要行式,那么就flush。
//当然,C++的std::endl具备刷新的效果。

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


int main()
{
        //使用C++的流式输出
    ///=------------------------------
    std::ofstream ofs("Common.hpp",std::ofstream::app);

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

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

    //因为C++里面的文件描述符是被保护起来的,因此想要访问就需要借助继承。
    // (*ofs.rdbuf())._M_file.fd();
    int myfd = helper(*ofs.rdbuf());
    dup2(1,myfd);//重定向到标准输出
    ofs<<"Test\n";
    ofs.flush();
    return 0;
}

为什么作上述工作:
解释:因为在linux用C++时,有时候向一些文件读写时,但是又无法直接拿到其文件名的情况。(比如网络套接字socket,其使用就是文件描述符的使用)
因为用C++的对象读写其实有许多便利,所以我们只需要打开一个文件,更换底层的文件描述符,这样就可以使用C++的IO来做操作了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值