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

相关推荐
YYYing.21 分钟前
【C++大型项目之高性能服务器框架 (九) 】协议抽象与Http服务器模块
服务器·c++·http·高性能·c/c++·后端框架
ly-2725322 分钟前
Ubuntu重启之后挂载盘符变更应该怎么修复
linux·ubuntu
Huangjin007_37 分钟前
【Linux 系统篇(四)】权限详解(一)
linux·运维·服务器
杯酒慰风尘1 小时前
chmod 权限计算器使用指南:读懂 755、rwx 与特殊权限
linux
ch0sen1pm1 小时前
不太懂 atomic?我花了一下午从 freelist 写到 CAS 无锁栈
c++
REDcker1 小时前
eBPF 运行时架构:Verifier、JIT、Map 与加载流程
linux·内核·ebpf·bpf
红豆诗人2 小时前
C++ string 和 vector 基础:从常用接口到模拟实现
c++·stl
良木生香2 小时前
【C++初阶】STL—— Stack & Queue 从入门到精通:容器适配器、迭代器与经典面试题
java·开发语言·c++·算法·zookeeper
小小晓.2 小时前
C++小白记:vector
开发语言·c++·算法
Zsy_0510032 小时前
【Linux】笔记01:基础命令
linux·运维·服务器