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来做操作了。

相关推荐
用户467244544994 分钟前
linux的网络配置
linux
Lueeee.23 分钟前
字符设备驱动---自己实现点LED
linux
Full Stack Developme24 分钟前
linux sudo su su - 三者区别
linux·运维·服务器
Byron Loong27 分钟前
【系统】Linux内核和发行版的关系
linux·运维·服务器
小镇学者1 小时前
【c++】C++字符串删除末尾字符的三种实现方法
java·开发语言·c++
SmartRadio1 小时前
在CH585M代码中如何精细化配置PMU(电源管理单元)和RAM保留
linux·c语言·开发语言·人工智能·单片机·嵌入式硬件·lora
济6171 小时前
linux(第十四期)--Uboot移植(2)-- 在U-Boot 中添加自己的开发板-- Ubuntu20.04
linux·运维·服务器
ben9518chen1 小时前
嵌入式linux操作系统简介
linux·运维·服务器
菜鸟笔记本1 小时前
linux设置定时备份mysql数据
linux·mysql·oracle
majingming1231 小时前
ubuntu下的交叉编译
linux·运维·ubuntu