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  SVCERR << "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  QFile tempFile(m_temp);
58  QFile targetFile(m_target);
59 
60  if (targetFile.exists()) {
61  if (!targetFile.remove()) {
62  SVCERR << "TempWriteFile: WARNING: Failed to remove existing target file " << m_target << " prior to moving temporary file " << m_temp << " to it" << endl;
63  }
64  }
65 
66  if (!tempFile.rename(m_target)) {
67  SVCERR << "TempWriteFile: Failed to rename temporary file " << m_temp << " to target " << m_target << endl;
68  throw FileOperationFailed(m_temp, "rename");
69  }
70 
71  m_temp = "";
72 }
73 
TempWriteFile(QString targetFileName)
QString m_temp
Definition: TempWriteFile.h:55
void moveToTarget()
Rename the temporary file to the target filename.
~TempWriteFile()
Destroy the temporary file object.
#define SVCERR
Definition: Debug.h:109
QString getTemporaryFilename()
Return the name of the temporary file.
QString m_target
Definition: TempWriteFile.h:54