dump_util: richer StdioFile type

This commit is contained in:
Justin Viiret
2017-06-26 14:25:44 +10:00
committed by Matthew Barr
parent 4edf1e4195
commit f762fb9af6
2 changed files with 39 additions and 35 deletions

View File

@@ -29,6 +29,8 @@
#ifndef DUMP_UTIL
#define DUMP_UTIL
#include "noncopyable.h"
#include <cstdio>
#include <memory>
#include <string>
@@ -41,18 +43,20 @@ namespace ue2 {
FILE *fopen_or_throw(const char *path, const char *mode);
/**
* \brief Helper function: returns a C stdio FILE* handle wrapped in
* a unique_ptr that takes care of closing the file on destruction.
*
* If the file cannot be opened, throws an exception.
* \brief Helper class: wraps C stdio FILE* handle and takes care of closing
* the file on destruction.
*/
inline
std::unique_ptr<FILE, decltype(&fclose)>
openStdioFile(const std::string &filename, const char *mode) {
return std::unique_ptr<FILE, decltype(&fclose)>(
fopen_or_throw(filename.c_str(), mode), &fclose);
}
class StdioFile : noncopyable {
public:
StdioFile(const std::string &filename, const char *mode)
: handle(fopen_or_throw(filename.c_str(), mode), &fclose) {}
// Implicit conversion to FILE* for use by stdio calls.
operator FILE *() { return handle.get(); }
private:
std::unique_ptr<FILE, decltype(&fclose)> handle;
};
} // namespace ue2