/* The software in this package is distributed under the GNU General Public License version 2 (with a special exception described below). A copy of GNU General Public License (GPL) is included in this distribution, in the file COPYING.GPL. As a special exception, if other files instantiate templates or use macros or inline functions from this file, or you compile this file and link it with other works to produce a work based on this file, this file does not by itself cause the resulting work to be covered by the GNU General Public License. However the source code for this file must still be made available in accordance with section (3) of the GNU General Public License. This exception does not invalidate any other reasons why a work based on this file might be covered by the GNU General Public License. */ #include #include #include #include #include #include #include using namespace std; void fdoutbuf::set_fd(int _fd) { fd = _fd; } int fdoutbuf::overflow (int_type c) { if (fd == -1) return c; if (c != EOF) { char z = c; if (write (fd, &z, 1) != 1) { return EOF; } } return c; } // write multiple characters std::streamsize fdoutbuf::xsputn (const char* s, std::streamsize num) { if (fd == -1) return (num); return write(fd,s,num); } oftmpstream::oftmpstream () : ostream(0) , file_mode(0644) { fd = -1; rdbuf(&buf); is_open = false; } oftmpstream::oftmpstream (const std::string &name) : ostream(0) , file_mode(0644) { fd = -1; rdbuf(&buf); is_open = false; open(name); } oftmpstream::~oftmpstream () { close(); } std::string oftmpstream::get_filename() { return realname; } std::string oftmpstream::get_tmp_filename() { return tmpname; } void oftmpstream::open (const string &name) { if (is_open) close(); realname = name; tmpname=name+".XXXXXX"; file_mode= 0644; char* chbuf=new char[tmpname.size()+1]; tmpname.copy(chbuf,tmpname.size()+1); chbuf[tmpname.size()]=0; fd=mkstemp(chbuf); tmpname=chbuf; delete[] chbuf; if (fd==-1) { string err="error creating temporary file "+tmpname; err+=": "; err+=strerror(errno); throw ios_base::failure(err); } buf.set_fd(fd); is_open = true; } void oftmpstream::close() { if (!is_open) return; fchmod (fd, file_mode); // fix/change mkstemp permissions fsync(fd); ::close (fd); if (rename (tmpname.c_str(), realname.c_str()) != 0) { string err="error renaming temporary file "+tmpname; err+=" to "+realname; err+=": "; err+=strerror(errno); throw ios_base::failure(err); } fd = -1; is_open = false; file_mode= 0644; } /** * @brief set file mode for the final file. * @param mode the fin al file mode. * * When called after open(), it determines the file mode which should * be used for the resulting file. */ void oftmpstream::set_file_mode(int mode) { file_mode= mode; } // eo oftmpstream::set_file_mode(int)