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@1359: SVCERR << "TempWriteFile: Failed to create temporary file in directory of " << m_target << ": " << temp.errorString() << 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@1359: QFile tempFile(m_temp); Chris@1359: QFile targetFile(m_target); Chris@1359: Chris@1359: if (targetFile.exists()) { Chris@1359: if (!targetFile.remove()) { Chris@1359: SVCERR << "TempWriteFile: WARNING: Failed to remove existing target file " << m_target << " prior to moving temporary file " << m_temp << " to it" << endl; Chris@1359: } Chris@1359: } Chris@1359: Chris@1359: if (!tempFile.rename(m_target)) { Chris@1359: SVCERR << "TempWriteFile: Failed to rename temporary file " << m_temp << " to target " << m_target << endl; Chris@674: throw FileOperationFailed(m_temp, "rename"); Chris@674: } Chris@674: Chris@674: m_temp = ""; Chris@674: } Chris@674: