#include "tempfile.h" #include "exceptionstream.h" #include #include #include #include temp_file_t::temp_file_t() : stream(), filename() { /* openbsd linker warns about using tmpnam/mktemp. would like to use mkstemp but fstream's open method only takes filename, and using fstream's ctr doesn't allow us to get access to the filenae...*/ this->open( tmpnam( NULL)); } temp_file_t::temp_file_t( const std::string& filename) : stream(), filename() { open( filename); } temp_file_t::~temp_file_t() { this->close(); } std::ofstream stream; std::string filename; void temp_file_t::close_and_move( const std::string& newfilename) /* Useful for moving a file to a different filename if creation has been successful. i.e. commit/rollback.*/ { this->stream.close(); assert( this->filename != ""); if ( system( (std::string() + "mv " + this->filename + " " + newfilename).c_str())) { throw exception_stream() << "Couldn't move `" << this->filename << "' to `" << newfilename + "'"; } this->filename = ""; } void temp_file_t::open( const std::string& newfilename) { this->close(); this->filename = newfilename; this->stream.open( this->filename.c_str()); if ( !this->stream) throw std::runtime_error( std::string( "Couldn't open temp file ") + this->filename); } void temp_file_t::close() { // gcc3.2/stlport makes stream invalid if we close it when it is not already open. if ( this->stream.is_open()) this->stream.close(); if ( !this->filename.empty()) remove( this->filename.c_str()); }