| 1 |
|
| 2 | |
| 3 | * Copyright (c) 2024 Meta Platforms, Inc. and affiliates.
|
| 4 | * Copyright (c) 2024 David Vernet <[email protected]>
|
| 5 |
|
| 6 | #include <errno.h>
|
| 7 | #include <fcntl.h>
|
| 8 | #include <stdio.h>
|
| 9 | #include <stdlib.h>
|
| 10 | #include <string.h>
|
| 11 | #include <unistd.h>
|
| 12 |
|
| 13 |
|
| 14 | static ssize_t read_text(const char *path, char *buf, size_t max_len)
|
| 15 | {
|
| 16 | ssize_t len;
|
| 17 | int fd;
|
| 18 |
|
| 19 | fd = open(path, O_RDONLY);
|
| 20 | if (fd < 0)
|
| 21 | return -errno;
|
| 22 |
|
| 23 | len = read(fd, buf, max_len - 1);
|
| 24 |
|
| 25 | if (len >= 0)
|
| 26 | buf[len] = 0;
|
| 27 |
|
| 28 | close(fd);
|
| 29 | return len < 0 ? -errno : len;
|
| 30 | }
|
| 31 |
|
| 32 |
|
| 33 | static ssize_t write_text(const char *path, char *buf, ssize_t len)
|
| 34 | {
|
| 35 | int fd;
|
| 36 | ssize_t written;
|
| 37 |
|
| 38 | fd = open(path, O_WRONLY | O_APPEND);
|
| 39 | if (fd < 0)
|
| 40 | return -errno;
|
| 41 |
|
| 42 | written = write(fd, buf, len);
|
| 43 | close(fd);
|
| 44 | return written < 0 ? -errno : written;
|
| 45 | }
|
| 46 |
|
| 47 | long file_read_long(const char *path)
|
| 48 | {
|
| 49 | char buf[128];
|
| 50 |
|
| 51 |
|
| 52 | if (read_text(path, buf, sizeof(buf)) <= 0)
|
| 53 | return -1;
|
| 54 |
|
| 55 | return atol(buf);
|
| 56 | }
|
| 57 |
|
| 58 | int file_write_long(const char *path, long val)
|
| 59 | {
|
| 60 | char buf[64];
|
| 61 | int ret;
|
| 62 |
|
| 63 | ret = sprintf(buf, "%ld", val);
|
| 64 | if (ret < 0)
|
| 65 | return ret;
|
| 66 |
|
| 67 | if (write_text(path, buf, ret) <= 0)
|
| 68 | return -1;
|
| 69 |
|
| 70 | return 0;
|
| 71 | }
|