Commit | Line | Data |
---|---|---|
e93545dd GE |
1 | #include <stdio.h> |
2 | #include <stdlib.h> | |
3 | #include <unistd.h> | |
4 | #include <sys/stat.h> | |
8d2c81e4 | 5 | #include <errno.h> |
e93545dd GE |
6 | |
7 | #include <oftmpstream.hxx> | |
8 | ||
9 | using namespace std; | |
10 | ||
11 | void fdoutbuf::set_fd(int _fd) { | |
12 | fd = _fd; | |
13 | } | |
14 | ||
15 | int fdoutbuf::overflow (int_type c) { | |
16 | if (fd == -1) | |
17 | return c; | |
18 | ||
19 | if (c != EOF) { | |
20 | char z = c; | |
21 | if (write (fd, &z, 1) != 1) { | |
22 | return EOF; | |
23 | } | |
24 | } | |
25 | return c; | |
26 | } | |
27 | // write multiple characters | |
28 | std::streamsize fdoutbuf::xsputn (const char* s, | |
29 | std::streamsize num) { | |
30 | if (fd == -1) | |
31 | return (num); | |
32 | ||
33 | return write(fd,s,num); | |
34 | } | |
35 | ||
36 | ||
37 | oftmpstream::oftmpstream () : ostream(0) { | |
38 | fd = -1; | |
39 | rdbuf(&buf); | |
40 | is_open = false; | |
41 | } | |
42 | ||
8ac198c4 | 43 | oftmpstream::oftmpstream (const std::string &name) : ostream(0) { |
e93545dd GE |
44 | fd = -1; |
45 | rdbuf(&buf); | |
46 | is_open = false; | |
47 | ||
48 | open(name); | |
49 | } | |
50 | ||
51 | oftmpstream::~oftmpstream () { | |
52 | close(); | |
53 | } | |
54 | ||
8ac198c4 | 55 | void oftmpstream::open (const string &name) |
e93545dd GE |
56 | { |
57 | if (is_open) | |
58 | close(); | |
59 | ||
60 | realname = name; | |
8ac198c4 | 61 | tmpname=name+".XXXXXX"; |
e93545dd GE |
62 | |
63 | char* chbuf=new char[tmpname.size()+1]; | |
64 | tmpname.copy(chbuf,tmpname.size()+1); | |
65 | chbuf[tmpname.size()]=0; | |
66 | fd=mkstemp(chbuf); | |
67 | tmpname=chbuf; | |
68 | delete[] chbuf; | |
69 | ||
70 | if (fd==-1) | |
71 | { | |
72 | string err="error creating temporary file "+tmpname; | |
73 | err+=": "; | |
74 | err+=strerror(errno); | |
75 | throw ios_base::failure(err); | |
76 | } | |
77 | ||
78 | buf.set_fd(fd); | |
79 | is_open = true; | |
80 | } | |
81 | ||
82 | void oftmpstream::close() | |
83 | { | |
84 | if (!is_open) | |
85 | return; | |
86 | ||
87 | fsync(fd); | |
88 | fchmod (fd, 0644); // fix mkstemp permissions | |
89 | ::close (fd); | |
90 | ||
91 | if (rename (tmpname.c_str(), realname.c_str()) != 0) | |
92 | { | |
93 | string err="error renaming temporary file "+tmpname; | |
94 | err+=" to "+realname; | |
95 | err+=": "; | |
96 | err+=strerror(errno); | |
97 | throw ios_base::failure(err); | |
98 | } | |
99 | ||
100 | fd = -1; | |
101 | is_open = false; | |
102 | } |