from std::ofstream
, no.
From a FILE*
, yes but it's not portable.
Here's a version for 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());
}