annotate base/TempWriteFile.cpp @ 1011:dbb7f0ab011e cxx11

CXX11 (-std=c++11) branch, to test build environments before making any code adaptations
author Chris Cannam
date Mon, 17 Nov 2014 15:31:07 +0000
parents e802e550a1f2
children 1c9bbbb6116a
rev   line source
Chris@674 1 /* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
Chris@674 2
Chris@674 3 /*
Chris@674 4 Sonic Visualiser
Chris@674 5 An audio file viewer and annotation editor.
Chris@674 6 Centre for Digital Music, Queen Mary, University of London.
Chris@674 7
Chris@674 8 This program is free software; you can redistribute it and/or
Chris@674 9 modify it under the terms of the GNU General Public License as
Chris@674 10 published by the Free Software Foundation; either version 2 of the
Chris@674 11 License, or (at your option) any later version. See the file
Chris@674 12 COPYING included with this distribution for more information.
Chris@674 13 */
Chris@674 14
Chris@674 15 #include "TempWriteFile.h"
Chris@674 16
Chris@674 17 #include "Exceptions.h"
Chris@674 18
Chris@674 19 #include <QTemporaryFile>
Chris@674 20 #include <QDir>
Chris@674 21 #include <iostream>
Chris@674 22
Chris@674 23 TempWriteFile::TempWriteFile(QString target) :
Chris@674 24 m_target(target)
Chris@674 25 {
Chris@674 26 QTemporaryFile temp(m_target + ".");
Chris@674 27 temp.setAutoRemove(false);
Chris@674 28 temp.open(); // creates the file and opens it atomically
Chris@674 29 if (temp.error()) {
Chris@843 30 cerr << "TempWriteFile: Failed to create temporary file in directory of " << m_target << ": " << temp.errorString() << endl;
Chris@674 31 throw FileOperationFailed(temp.fileName(), "creation");
Chris@674 32 }
Chris@674 33
Chris@674 34 m_temp = temp.fileName();
Chris@675 35 temp.close(); // does not remove the file
Chris@674 36 }
Chris@674 37
Chris@674 38 TempWriteFile::~TempWriteFile()
Chris@674 39 {
Chris@674 40 if (m_temp != "") {
Chris@674 41 QDir dir(QFileInfo(m_temp).dir());
Chris@674 42 dir.remove(m_temp);
Chris@674 43 }
Chris@674 44 }
Chris@674 45
Chris@674 46 QString
Chris@674 47 TempWriteFile::getTemporaryFilename()
Chris@674 48 {
Chris@674 49 return m_temp;
Chris@674 50 }
Chris@674 51
Chris@674 52 void
Chris@674 53 TempWriteFile::moveToTarget()
Chris@674 54 {
Chris@674 55 if (m_temp == "") return;
Chris@674 56
Chris@674 57 QDir dir(QFileInfo(m_temp).dir());
Chris@674 58 // According to http://doc.trolltech.com/4.4/qdir.html#rename
Chris@674 59 // some systems fail, if renaming over an existing file.
Chris@674 60 // Therefore, delete first the existing file.
Chris@674 61 if (dir.exists(m_target)) dir.remove(m_target);
Chris@674 62 if (!dir.rename(m_temp, m_target)) {
Chris@843 63 cerr << "TempWriteFile: Failed to rename temporary file " << m_temp << " to target " << m_target << endl;
Chris@674 64 throw FileOperationFailed(m_temp, "rename");
Chris@674 65 }
Chris@674 66
Chris@674 67 m_temp = "";
Chris@674 68 }
Chris@674 69