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

如题

先上代码:

核心代码

cpp 复制代码
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具备刷新的效果。

cpp 复制代码
#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来做操作了。

相关推荐
偶像你挑的噻14 分钟前
5-Linux驱动开发-关于LED的字符设备
linux·运维·驱动开发·stm32·嵌入式硬件
赵财猫._.1 小时前
Native API开发:C++与ArkTS混合编程实战
开发语言·c++·harmonyos
i***48611 小时前
【漏洞复现】CVE-2019-11043(PHP远程代码执行漏洞)信息安全论文_含漏洞复现完整过程_含Linux环境go语言编译环境安装
linux·golang·php
普通网友2 小时前
基于C++的操作系统开发
开发语言·c++·算法
2501_941111343 小时前
C++中的策略模式高级应用
开发语言·c++·算法
普通网友4 小时前
C++与Qt图形开发
开发语言·c++·算法
AA陈超5 小时前
UE5笔记:GetWorld()->SpawnActorDeferred()
c++·笔记·学习·ue5·虚幻引擎
普通网友5 小时前
C++中的适配器模式
开发语言·c++·算法
百***66175 小时前
linux上redis升级
linux·运维·redis
无敌最俊朗@5 小时前
力扣hot100-160-相交链表
c++