FileWrapper

class FileWrapper

Wrapper for c-stype FILE with RAII.

Public Types

enum SpecialStream

Used to construct special stream handlers for cout and cerr.

Values:

Cout
Cerr
enum Status

return status when opening the files

Values:

Success
Failed

Public Functions

FileWrapper()

default constructor

FileWrapper(const std::string &fname, const std::string &mode)

Construct a FileWrapper and tries to open the file fname in mode mode.

This method will die if the file was not found

Parameters
  • fname: The name of the file to open
  • mode: The open mode, e.g. “r” for read mode (see docs of std::fopen)

FileWrapper(SpecialStream stream, bool forceFlushOnClose)

Construct a FileWrapper for console output.

Note
See also open(SpecialStream, bool))
Parameters
  • stream: The SpecialStream to dump to.
  • forceFlushOnClose: If true, flushes to the stream when the object is closed.

FileWrapper(FileWrapper&&)

move constructor

FileWrapper &operator=(FileWrapper&&)

move assignment

Status open(const std::string &fname, const std::string &mode)

Open a file in a given mode.

Return
Status::Success if the file was open succesfully, Status::Failed otherwise
Parameters
  • fname: The name of the file to open
  • mode: The open mode, e.g. “r” for read mode (see docs of std::fopen)

Status open(SpecialStream stream, bool forceFlushOnClose)

Set the wrapper to write to a special stream.

Return
success status
Parameters
  • stream: stdout or stderr
  • forceFlushOnClose: If set to true, the buffer will be flushed when close() is called.

FILE *get()

Return
the C-style file handler

void close()

Close the current handler.

This does not need to be called manually unless reopening a new file, since it will be called in the destructor.

If the handler was pointing to a file, the file is close. If the handler was pointing to a special stream (cout, cerr), fflush may be called (see forceFlushOnClose parameter in open(SpecialStream, bool)) but the stream is not closed. If the handler did not point to anything, nothing happens.

void fread(void *ptr, size_t size, size_t count)

Wrapper around std::fread. Throws an exception if reading failed.