svcore  1.9
TempWriteFile.cpp
Go to the documentation of this file.
00001 /* -*- c-basic-offset: 4 indent-tabs-mode: nil -*-  vi:set ts=8 sts=4 sw=4: */
00002 
00003 /*
00004     Sonic Visualiser
00005     An audio file viewer and annotation editor.
00006     Centre for Digital Music, Queen Mary, University of London.
00007     
00008     This program is free software; you can redistribute it and/or
00009     modify it under the terms of the GNU General Public License as
00010     published by the Free Software Foundation; either version 2 of the
00011     License, or (at your option) any later version.  See the file
00012     COPYING included with this distribution for more information.
00013 */
00014 
00015 #include "TempWriteFile.h"
00016 
00017 #include "Exceptions.h"
00018 
00019 #include <QTemporaryFile>
00020 #include <QDir>
00021 #include <iostream>
00022 
00023 TempWriteFile::TempWriteFile(QString target) :
00024     m_target(target)
00025 {
00026     QTemporaryFile temp(m_target + ".");
00027     temp.setAutoRemove(false);
00028     temp.open(); // creates the file and opens it atomically
00029     if (temp.error()) {
00030         cerr << "TempWriteFile: Failed to create temporary file in directory of " << m_target << ": " << temp.errorString() << endl;
00031         throw FileOperationFailed(temp.fileName(), "creation");
00032     }
00033     
00034     m_temp = temp.fileName();
00035     temp.close(); // does not remove the file
00036 }
00037 
00038 TempWriteFile::~TempWriteFile()
00039 {
00040     if (m_temp != "") {
00041         QDir dir(QFileInfo(m_temp).dir());
00042         dir.remove(m_temp);
00043     }
00044 }
00045 
00046 QString
00047 TempWriteFile::getTemporaryFilename()
00048 {
00049     return m_temp;
00050 }
00051 
00052 void
00053 TempWriteFile::moveToTarget()
00054 {
00055     if (m_temp == "") return;
00056 
00057     QDir dir(QFileInfo(m_temp).dir());
00058     // According to  http://doc.trolltech.com/4.4/qdir.html#rename
00059     // some systems fail, if renaming over an existing file.
00060     // Therefore, delete first the existing file.
00061     if (dir.exists(m_target)) dir.remove(m_target);
00062     if (!dir.rename(m_temp, m_target)) {
00063         cerr << "TempWriteFile: Failed to rename temporary file " << m_temp << " to target " << m_target << endl;
00064         throw FileOperationFailed(m_temp, "rename");
00065     }
00066 
00067     m_temp = "";
00068 }
00069