C++ 如何检测ofstream是否正在写入/dev/null
是否有任何(简单)方法可以检测C++ 如何检测ofstream是否正在写入/dev/null,c++,fstream,C++,Fstream,是否有任何(简单)方法可以检测中的某个函数()中的ofs是否正在写入/dev/null #include <fstream> some_function(std::ofstream & ofs); int main() { std::ofstream ofs("/dev/null"); ofs << "lorem ipsum"; some_function(ofs); // Testing in here return 0;
中的某个函数()
中的ofs
是否正在写入/dev/null
#include <fstream>
some_function(std::ofstream & ofs);
int main()
{
std::ofstream ofs("/dev/null");
ofs << "lorem ipsum";
some_function(ofs); // Testing in here
return 0;
}
#包括
一些_函数(std::ofstream&ofs);
int main()
{
std::ofs流(“/dev/null”);
ofs
如果ofs
正在写入/dev/null
,是否有(简单的)方法检测中的某些函数(std::ofstreamofs)
#include <fstream>
some_function(std::ofstream & ofs);
int main()
{
std::ofstream ofs("/dev/null");
ofs << "lorem ipsum";
some_function(ofs); // Testing in here
return 0;
}
不,没有
您正在寻找获取该信息的方法,这一事实向我表明,某些函数
具有分支代码,这取决于您是否正在写入/dev/null
您可以通过向函数添加另一个参数来解决该问题,并让客户机代码向您提供该信息
void some_function(std::ofstream& ofs, bool isDevNull);
并将其用作:
std::ofstream ofs ("/dev/null", std::ofstream::out);
ofs << "lorem ipsum";
some_function(ofs, true);
std::ofstreamofs(“/dev/null”,std::ofstream::out);
ofs来自std::of Stream
,编号
从文件*
,可以,但它不可移植
以下是linux的一个版本:
#include <fstream>
#include <unistd.h>
#include <stdio.h>
#include <memory>
#include <stdexcept>
#include <iostream>
#include <sstream>
struct file_closer
{
void operator()(FILE*p) const noexcept
{
if (p)
fclose(p);
}
};
auto open_write(const char* path) -> std::unique_ptr<FILE, file_closer>
{
auto result = std::unique_ptr<FILE, file_closer>(fopen(path, "w"));
if (!result.get())
throw std::runtime_error("not opened");
return result;
}
size_t do_readlink(const char* path, char* buffer, size_t buflen)
{
auto len = readlink(path, buffer, buflen);
if (len < 0)
throw std::runtime_error("failed to read link");
return size_t(len);
}
bool is_dev_null(FILE* fp)
{
int fd = fileno(fp);
std::ostringstream procpath;
procpath << "/proc/self/fd/" << fd;
auto spath = procpath.str();
size_t bufs = 1024;
std::string path(bufs, ' ');
auto len = do_readlink(spath.c_str(), &path[0], bufs);
while(len > bufs)
{
bufs = len;
path.resize(bufs);
len = do_readlink(spath.c_str(), &path[0], bufs);
}
path.resize(len);
return path == "/dev/null";
}
int main()
{
auto fp = open_write("/dev/null");
std::cout << is_dev_null(fp.get());
}
#包括
#包括
#包括
#包括
#包括
#包括
#包括
结构文件
{
void运算符()(文件*p)常量noexcept
{
如果(p)
fclose(p);
}
};
自动打开\u写入(常量字符*路径)->std::unique\u ptr
{
自动结果=std::unique_ptr(fopen(路径,“w”);
如果(!result.get())
抛出std::runtime_错误(“未打开”);
返回结果;
}
大小\u t do\u readlink(常量字符*路径、字符*缓冲区、大小\u t buflen)
{
自动len=readlink(路径、缓冲区、buflen);
if(len<0)
抛出std::runtime_错误(“读取链接失败”);
返回大小(len);
}
bool为_dev_null(文件*fp)
{
int fd=文件编号(fp);
std::ostringstream procpath;
procpath这并没有解决这个问题,但是您不需要调用ofs.close()的
。析构函数会这样做。@Frank不确定这是否是一个骗局。快速破解:在调用前后检查/dev/null
的大小;-);-);-)更可能的是,这个问题:你想在这里解决什么?你的问题是学术性的,还是你想解决一个特定的问题?我同意。分离关注点。你可以这样做,也可以创建一个包装类,它存储用于打开流的目录信息。通过这种方式,它不与Dev绑定,例如:production env。