Search code examples
c++fstream

How to detect if ofstream is writing to /dev/null


Is there any (simple) way to detect in some_function() if ofs is writing to /dev/null or not?

#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;
}

Solution

  • is there any (simple) way to detect in some_function(std::ofstream ofs) if ofs is writing to /dev/null or not?

    No, there isn't.

    The fact that you are looking for a way to get that information indicates to me that some_function has branching code depending on whether you are writing to /dev/null or not.

    You can address that problem by adding another argument to the function and let the client code provide that information to you.

    void some_function(std::ofstream& ofs, bool isDevNull);
    

    and use it as:

    std::ofstream ofs ("/dev/null", std::ofstream::out);
    ofs << "lorem ipsum";
    some_function(ofs, true);