File indexing completed on 2024-04-14 05:34:44

0001 /*
0002     SPDX-FileCopyrightText: 2018 Milian Wolff <mail@milianw.de>
0003 
0004     SPDX-License-Identifier: LGPL-2.1-or-later
0005 */
0006 
0007 #ifndef TEMPFILE_H
0008 #define TEMPFILE_H
0009 
0010 #include <boost/filesystem.hpp>
0011 #include <fcntl.h>
0012 #include <unistd.h>
0013 
0014 #include <fstream>
0015 #include <sstream>
0016 
0017 struct TempFile
0018 {
0019     TempFile()
0020         : path(boost::filesystem::unique_path())
0021         , fileName(path.native())
0022     {
0023     }
0024 
0025     ~TempFile()
0026     {
0027         boost::filesystem::remove(path);
0028         close();
0029     }
0030 
0031     bool open()
0032     {
0033         fd = ::open(fileName.c_str(), O_CREAT | O_CLOEXEC | O_RDWR, 0644);
0034         return fd != -1;
0035     }
0036 
0037     void close()
0038     {
0039         if (fd != -1) {
0040             ::close(fd);
0041         }
0042     }
0043 
0044     std::string readContents() const
0045     {
0046         // open in binary mode to really read everything
0047         // we want to ensure that the contents are really clean
0048         std::ifstream ifs(fileName, std::ios::binary);
0049         return {std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>()};
0050     }
0051 
0052     const boost::filesystem::path path;
0053     const std::string fileName;
0054     int fd = -1;
0055 };
0056 
0057 #endif