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

相关推荐
vortex514 分钟前
探索 Shell:选择适合你的命令行利器 bash, zsh, fish, dash, sh...
linux·开发语言·bash·shell·dash
HUN金克斯26 分钟前
C++/C函数
c语言·开发语言·c++
慢半拍iii26 分钟前
数据结构——F/图
c语言·开发语言·数据结构·c++
GalaxyPokemon38 分钟前
LeetCode - 148. 排序链表
linux·算法·leetcode
懒羊羊大王呀1 小时前
Ubuntu20.04中 Redis 的安装和配置
linux·redis
iceslime1 小时前
旅行商问题(TSP)的 C++ 动态规划解法教学攻略
数据结构·c++·算法·算法设计与分析
虾球xz1 小时前
CppCon 2015 学习:3D Face Tracking and Reconstruction using Modern C++
开发语言·c++·学习·3d
杰哥技术分享1 小时前
在 CentOS 上安装 Docker 和 Docker Compose 并配置使用国内镜像源
linux·docker·centos
知更鸟呆呆1 小时前
【Linux操作系统】基础开发工具(yum、vim、gcc/g++)
linux·运维·vim
xiangyong581 小时前
ubuntu系统文件误删(/lib/x86_64-linux-gnu/libc.so.6)修复方案 [成功解决]
linux·ubuntu·gnu