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

相关推荐
gb421528711 分钟前
linux系统中如何在root用户中将某个文件夹目录的权限赋值给其它用户(主要说的是 方法 1)
linux
chennn1226 分钟前
c++相关学习
开发语言·c++·学习
qq_3395548230 分钟前
linux串口驱动学习
linux
拾光Ծ41 分钟前
【Linux】入门指南:基础指令详解Part Two
linux·运维·服务器
m0_552200821 小时前
《UE5_C++多人TPS完整教程》学习笔记61 ——《P62 武器开火特效(Fire Weapon Effects)》
c++·游戏·ue5
AA陈超1 小时前
虚幻引擎5 GAS开发俯视角RPG游戏 P05-04 使用效果应用游戏标签
c++·游戏·ue5·游戏引擎·虚幻
峰顶听歌的鲸鱼2 小时前
38.Shell脚本编程2
linux·运维·服务器·笔记·学习方法
---学无止境---2 小时前
Linux工作队列workqueue的实现
linux
dessler2 小时前
Elasticsearch(ES)简介与入门
linux·运维·hdfs
晴天¥3 小时前
Linux操作系统如何使用ISO镜像文件来搭建本地镜像源?
linux·运维·centos