4 author: José Bollo <jose.bollo@iot.bzh>
6 Licensed under the Apache License, Version 2.0 (the "License");
7 you may not use this file except in compliance with the License.
8 You may obtain a copy of the License at
10 http://www.apache.org/licenses/LICENSE-2.0
12 Unless required by applicable law or agreed to in writing, software
13 distributed under the License is distributed on an "AS IS" BASIS,
14 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 See the License for the specific language governing permissions and
16 limitations under the License.
28 #include "utils-file.h"
30 /* alias for getfile_at(AT_FDCWD, file, content, size) */
31 int getfile(const char *file, char **content, size_t *size)
33 return getfile_at(AT_FDCWD, file, content, size);
37 * Reads the 'file' relative to 'dfd' (see openat) in a freshly
38 * allocated memory and returns it in 'content' and 'size' (if not NULL).
39 * To help in reading text files, a pending null is added at the
41 * Return 0 in case of success or else -1 and set 'errno'.
43 int getfile_at(int dfd, const char *file, char **content, size_t *size)
53 rc = openat(dfd, file, O_RDONLY);
59 } else if (!S_ISREG(s.st_mode)) {
63 sz = (size_t)s.st_size;
71 while (!rc && i < sz) {
72 rsz = read(f, r + i, sz - i);
77 else if (errno != EINTR && errno != EAGAIN) {
96 /* alias for putfile_at(AT_FDCWD, file, content, size) */
97 int putfile(const char *file, const void *content, size_t size)
99 return putfile_at(AT_FDCWD, file, content, size);
102 int putfile_at(int dfd, const char *file, const void *content, size_t size)
108 rc = openat(dfd, file, O_WRONLY|O_CREAT|O_TRUNC, 0666);
110 if (size == (size_t)(ssize_t)-1)
111 size = strlen(content);
115 while (!rc && i < size) {
116 wsz = write(f, content + i, size - i);
119 else if (errno != EINTR && errno != EAGAIN) {
120 unlinkat(dfd, file, 0);