Chris@674: /* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */ Chris@674: Chris@674: /* Chris@674: Sonic Visualiser Chris@674: An audio file viewer and annotation editor. Chris@674: Centre for Digital Music, Queen Mary, University of London. Chris@674: Chris@674: This program is free software; you can redistribute it and/or Chris@674: modify it under the terms of the GNU General Public License as Chris@674: published by the Free Software Foundation; either version 2 of the Chris@674: License, or (at your option) any later version. See the file Chris@674: COPYING included with this distribution for more information. Chris@674: */ Chris@674: Chris@674: #include "TempWriteFile.h" Chris@674: Chris@674: #include "Exceptions.h" Chris@674: Chris@674: #include Chris@674: #include Chris@674: #include Chris@674: Chris@674: TempWriteFile::TempWriteFile(QString target) : Chris@674: m_target(target) Chris@674: { Chris@674: QTemporaryFile temp(m_target + "."); Chris@674: temp.setAutoRemove(false); Chris@674: temp.open(); // creates the file and opens it atomically Chris@674: if (temp.error()) { Chris@674: std::cerr << "TempWriteFile: Failed to create temporary file in directory of " << m_target.toStdString() << ": " << temp.errorString().toStdString() << std::endl; Chris@674: throw FileOperationFailed(temp.fileName(), "creation"); Chris@674: } Chris@674: Chris@674: m_temp = temp.fileName(); Chris@675: temp.close(); // does not remove the file Chris@674: } Chris@674: Chris@674: TempWriteFile::~TempWriteFile() Chris@674: { Chris@674: if (m_temp != "") { Chris@674: QDir dir(QFileInfo(m_temp).dir()); Chris@674: dir.remove(m_temp); Chris@674: } Chris@674: } Chris@674: Chris@674: QString Chris@674: TempWriteFile::getTemporaryFilename() Chris@674: { Chris@674: return m_temp; Chris@674: } Chris@674: Chris@674: void Chris@674: TempWriteFile::moveToTarget() Chris@674: { Chris@674: if (m_temp == "") return; Chris@674: Chris@674: QDir dir(QFileInfo(m_temp).dir()); Chris@674: // According to http://doc.trolltech.com/4.4/qdir.html#rename Chris@674: // some systems fail, if renaming over an existing file. Chris@674: // Therefore, delete first the existing file. Chris@674: if (dir.exists(m_target)) dir.remove(m_target); Chris@674: if (!dir.rename(m_temp, m_target)) { Chris@674: std::cerr << "TempWriteFile: Failed to rename temporary file " << m_temp.toStdString() << " to target " << m_target.toStdString() << std::endl; Chris@674: throw FileOperationFailed(m_temp, "rename"); Chris@674: } Chris@674: Chris@674: m_temp = ""; Chris@674: } Chris@674: