+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <errno.h>
+
+#include "util.h"
+
+using namespace std;
+
+int make_tempfile(const std::string &contents)
+{
+ char filename[] = "/tmp/cubemap.XXXXXX";
+ int fd = mkstemp(filename);
+ if (fd == -1) {
+ perror("mkstemp");
+ return -1;
+ }
+
+ if (unlink(filename) == -1) {
+ perror("unlink");
+ // Can still continue;
+ }
+
+ const char *ptr = contents.data();
+ size_t to_write = contents.size();
+ while (to_write > 0) {
+ ssize_t ret = write(fd, ptr, to_write);
+ if (ret == -1) {
+ perror("write");
+ close(fd);
+ return -1;
+ }
+
+ ptr += ret;
+ to_write -= ret;
+ }
+
+ return fd;
+}
+
+bool read_tempfile(int fd, std::string *contents)
+{
+ if (lseek(fd, 0, SEEK_SET) == -1) {
+ perror("lseek");
+ return false;
+ }
+
+ char buf[4096];
+ for ( ;; ) {
+ ssize_t ret = read(fd, buf, sizeof(buf));
+ if (ret == -1) {
+ perror("read");
+ return false;
+ }
+ if (ret == 0) {
+ // EOF.
+ break;
+ }
+
+ contents->append(string(buf, buf + ret));
+ }
+
+ int ret;
+ do {
+ ret = close(fd); // Implicitly deletes the files.
+ } while (ret == -1 && errno == EINTR);
+
+ if (ret == -1) {
+ perror("close");
+ // Can still continue.
+ }
+
+ return true;
+}