]> git.sesse.net Git - cubemap/blob - util.cpp
Fix a spurious warning.
[cubemap] / util.cpp
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4 #include <errno.h>
5
6 #include "util.h"
7
8 using namespace std;
9
10 int make_tempfile(const std::string &contents)
11 {
12         char filename[] = "/tmp/cubemap.XXXXXX";
13         int fd = mkstemp(filename);
14         if (fd == -1) {
15                 perror("mkstemp");
16                 return -1;
17         }
18
19         if (unlink(filename) == -1) {
20                 perror("unlink");
21                 // Can still continue;
22         }
23
24         const char *ptr = contents.data();
25         size_t to_write = contents.size();
26         while (to_write > 0) {
27                 ssize_t ret = write(fd, ptr, to_write);
28                 if (ret == -1) {
29                         perror("write");
30                         close(fd);
31                         return -1;
32                 }
33
34                 ptr += ret;
35                 to_write -= ret;
36         }
37
38         return fd;
39 }
40
41 bool read_tempfile(int fd, std::string *contents)
42 {
43         if (lseek(fd, 0, SEEK_SET) == -1) {
44                 perror("lseek");
45                 return false;
46         }
47
48         char buf[4096];
49         for ( ;; ) {
50                 ssize_t ret = read(fd, buf, sizeof(buf));
51                 if (ret == -1) {
52                         perror("read");
53                         return false;
54                 }
55                 if (ret == 0) {
56                         // EOF.
57                         break;
58                 }
59
60                 contents->append(string(buf, buf + ret));
61         }
62
63         int ret;
64         do {
65                 ret = close(fd);  // Implicitly deletes the files.
66         } while (ret == -1 && errno == EINTR);
67         
68         if (ret == -1) {
69                 perror("close");
70                 // Can still continue.
71         }
72
73         return true;
74 }