d19241a21e8565e55847c4cac6371e9f697756e9
[ardour.git] / libs / audiographer / audiographer / sndfile / tmp_file.h
1 #ifndef AUDIOGRAPHER_TMP_FILE_H
2 #define AUDIOGRAPHER_TMP_FILE_H
3
4 #include <cstdio>
5 #include <string>
6
7 #include <glib.h>
8 #include <pbd/gstdio_compat.h>
9
10 #include "sndfile_writer.h"
11 #include "sndfile_reader.h"
12
13 namespace AudioGrapher
14 {
15
16 /// A temporary file deleted after this class is destructed
17 template<typename T = DefaultSampleType>
18 class TmpFile : public SndfileWriter<T>, public SndfileReader<T>
19 {
20   public:
21
22         /// \a filename_template must match the requirements for mkstemp, i.e. end in "XXXXXX"
23         TmpFile (char * filename_template, int format, ChannelCount channels, framecnt_t samplerate)
24                 : SndfileHandle (g_mkstemp(filename_template), true, SndfileBase::ReadWrite, format, channels, samplerate)
25                 , filename (filename_template)
26         {}
27
28         TmpFile (int format, ChannelCount channels, framecnt_t samplerate)
29           : SndfileHandle (fileno (tmpfile()), true, SndfileBase::ReadWrite, format, channels, samplerate)
30         {}
31
32         TmpFile (TmpFile const & other) : SndfileHandle (other) {}
33         using SndfileHandle::operator=;
34
35         ~TmpFile()
36         {
37                 /* explicitly close first, some OS (yes I'm looking at you windows)
38                  * cannot delet files that are still open
39                  */
40                 if (!filename.empty()) {
41                         SndfileBase::close();
42                         std::remove(filename.c_str());
43                 }
44         }
45
46   private:
47         std::string filename;
48 };
49
50 } // namespace
51
52 #endif // AUDIOGRAPHER_TMP_FILE_H