forked from confluentinc/kibosh
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathio.c
More file actions
131 lines (117 loc) · 2.71 KB
/
io.c
File metadata and controls
131 lines (117 loc) · 2.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
/**
* Copyright 2017 Confluent Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
#include "io.h"
#include "log.h"
#include "util.h"
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
ssize_t safe_write(int fd, const void *b, size_t c)
{
int res;
while (c > 0) {
res = write(fd, b, c);
if (res < 0) {
if (errno != EINTR)
return -errno;
} else {
c -= res;
b = (char *)b + res;
}
}
return 0;
}
int write_string_to_file(const char *path, const char *str)
{
int fd, ret;
fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0666);
if (fd < 0) {
return -errno;
}
ret = safe_write(fd, str, strlen(str));
if (ret < 0) {
close(fd);
return ret;
}
if (close(fd) < 0) {
return -errno;
}
return 0;
}
ssize_t safe_read(int fd, void *b, size_t c)
{
int res;
size_t cnt = 0;
while (cnt < c) {
res = read(fd, b, c - cnt);
if (res <= 0) {
if (res == 0)
return cnt;
if (errno != EINTR)
return -errno;
} else {
cnt += res;
b = (char *)b + res;
}
}
return cnt;
}
int read_string_from_fd(int fd, char *buf, size_t buf_len)
{
int ret = safe_read(fd, buf, buf_len - 1);
if (ret < 0) {
return ret;
}
buf[ret] = '\0';
return 0;
}
int read_string_from_file(const char *path, char *buf, size_t buf_len)
{
int fd, ret;
fd = open(path, O_RDONLY, 0666);
if (fd < 0) {
return -errno;
}
ret = read_string_from_fd(fd, buf, buf_len);
if (ret < 0) {
close(fd);
return ret;
}
if (close(fd) < 0) {
return -errno;
}
return 0;
}
int duplicate_fd(int dest_fd, int src_fd)
{
char buf[128];
int ret;
while (1) {
int nread = safe_read(src_fd, buf, sizeof(buf));
if (nread <= 0)
return nread;
ret = safe_write(dest_fd, buf, nread);
if (ret < 0)
return ret;
}
}
// vim: ts=4:sw=4:tw=99:et