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