/* Whole files. */ #ifndef SAFEC_FILE_H #define SAFEC_FILE_H #include "text.h" #include #if defined(__clang__) #pragma clang assume_nonnull begin #endif /* Both return 0, or what went wrong as an errno value (ENOENT, ENOMEM, ...), like the pthread functions. Not a RESULT: there is no value to go with it. */ /* Adds the file's bytes to *out: 0, or an errno value and *out as it was. */ SAFEC_MUST_USE static inline int file_read(const char *__null_terminated path, struct text *out) { FILE *_Owned _Nullable f = fopen(path, "rb"); if (!f) return errno; char part[4096]; int ok = 1, why = 0; size_t n = 0, before = out->len; do { n = fread(part, 1, sizeof part, f); if (n > sizeof part || !text_add(out, part, n)) ok = 0, why = ENOMEM; } while (ok && n == sizeof part); if (ferror(f)) ok = 0, why = errno ? errno : EIO; fclose(f); if (!ok) { out->len = before; return why; } return 0; } /* Replaces the file: 0, or an errno value and the old file as it was. It is written to 'path.tmp' and renamed, so a reader sees all of the old or all of the new. */ SAFEC_MUST_USE static inline int file_write(const char *__null_terminated path, struct str bytes) { char tmp[1024]; int n = snprintf(tmp, sizeof tmp, "%s.tmp", path); if (n < 0 || (size_t)n >= sizeof tmp) return ENAMETOOLONG; FILE *_Owned _Nullable f = fopen(tmp, "wb"); if (!f) return errno; int ok = fwrite(bytes.p, 1, bytes.len, f) == bytes.len; if (fclose(f) != 0) ok = 0; int why = errno ? errno : EIO; if (ok && rename(tmp, path) == 0) return 0; why = errno ? errno : why; remove(tmp); return why; } #if defined(__clang__) #pragma clang assume_nonnull end #endif #endif