Consider the following C code:
void openFile(const char *mode, char *filename, FILE **fileptr)
{
...
*fileptr = fopen(filename, mode);
...
}
FILE *logstream;
if (LOG_FILE_ENABLED)
{
openFile("w", "mylogfile.txt", logstream);
}
else
{
logstream = stderr;
}
fprintf(logstream, "[DEBUG] Some debug message...
");
fclose(logstream);
I am attempting to translate this to idiomatic C++. How can I overload openFile()
such that it takes a std::ofstream
, but keep logstream
stream-agnostic? I was assuming it would be something like this:
void openFile(const char *mode, char *filename, std::ofstream &ofs)
{
...
ofs.open(filename);
...
}
std::ostream logstream;
if (LOG_FILE_ENABLED)
{
logstream = std::ofstream();
openFile("w", "mylogfile.txt", logstream);
}
else
{
logstream = std::cerr;
}
logstream << "[DEBUG] Some debug message..." << std::endl;
logstream.close();
However this is apparently wildly incorrect - you can't even initialize a plain std::ostream
like that. How should I handle this - preferably while avoiding the use of raw pointers?