safe-c-std/file.h
Raw file ยท Directory on GitHub
1/* Whole files. */
2#ifndef SAFEC_FILE_H
3#define SAFEC_FILE_H
4#include "text.h"
5#include <errno.h>
6#if defined(__clang__)
7#pragma clang assume_nonnull begin
8#endif
9
10/* Both return 0, or what went wrong as an errno value (ENOENT, ENOMEM, ...),
11 like the pthread functions. Not a RESULT: there is no value to go with it. */
12
13/* Adds the file's bytes to *out: 0, or an errno value and *out as it was. */
14SAFEC_MUST_USE static inline int file_read(const char *__null_terminated path, struct text *out) {
15 FILE *_Owned _Nullable f = fopen(path, "rb");
16 if (!f)
17 return errno;
18 char part[4096];
19 int ok = 1, why = 0;
20 size_t n = 0, before = out->len;
21 do {
22 n = fread(part, 1, sizeof part, f);
23 if (n > sizeof part || !text_add(out, part, n))
24 ok = 0, why = ENOMEM;
25 } while (ok && n == sizeof part);
26 if (ferror(f))
27 ok = 0, why = errno ? errno : EIO;
28 fclose(f);
29 if (!ok) {
30 out->len = before;
31 return why;
32 }
33 return 0;
34}
35
36/* Replaces the file: 0, or an errno value and the old file as it was. It is
37 written to 'path.tmp' and renamed, so a reader sees all of the old or all of
38 the new. */
39SAFEC_MUST_USE static inline int file_write(const char *__null_terminated path, struct str bytes) {
40 char tmp[1024];
41 int n = snprintf(tmp, sizeof tmp, "%s.tmp", path);
42 if (n < 0 || (size_t)n >= sizeof tmp)
43 return ENAMETOOLONG;
44 FILE *_Owned _Nullable f = fopen(tmp, "wb");
45 if (!f)
46 return errno;
47 int ok = fwrite(bytes.p, 1, bytes.len, f) == bytes.len;
48 if (fclose(f) != 0)
49 ok = 0;
50 int why = errno ? errno : EIO;
51 if (ok && rename(tmp, path) == 0)
52 return 0;
53 why = errno ? errno : why;
54 remove(tmp);
55 return why;
56}
57
58#if defined(__clang__)
59#pragma clang assume_nonnull end
60#endif
61#endif
62