Mercurial > hg > svcore
comparison base/TempWriteFile.cpp @ 674:920e3880f7b4
* Add TempWriteFile abstraction, use it when exporting audio to avoid clobbering existing file before export is complete
author | Chris Cannam |
---|---|
date | Tue, 29 Mar 2011 17:30:23 +0100 |
parents | |
children | 341e4e1a6ed3 |
comparison
equal
deleted
inserted
replaced
673:a1ae2c1f80ab | 674:920e3880f7b4 |
---|---|
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 | |
23 TempWriteFile::TempWriteFile(QString target) : | |
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 std::cerr << "TempWriteFile: Failed to create temporary file in directory of " << m_target.toStdString() << ": " << temp.errorString().toStdString() << std::endl; | |
31 throw FileOperationFailed(temp.fileName(), "creation"); | |
32 } | |
33 | |
34 m_temp = temp.fileName(); | |
35 temp.close(); | |
36 } | |
37 | |
38 TempWriteFile::~TempWriteFile() | |
39 { | |
40 if (m_temp != "") { | |
41 QDir dir(QFileInfo(m_temp).dir()); | |
42 dir.remove(m_temp); | |
43 } | |
44 } | |
45 | |
46 QString | |
47 TempWriteFile::getTemporaryFilename() | |
48 { | |
49 return m_temp; | |
50 } | |
51 | |
52 void | |
53 TempWriteFile::moveToTarget() | |
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 std::cerr << "TempWriteFile: Failed to rename temporary file " << m_temp.toStdString() << " to target " << m_target.toStdString() << std::endl; | |
64 throw FileOperationFailed(m_temp, "rename"); | |
65 } | |
66 | |
67 m_temp = ""; | |
68 } | |
69 |