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