diff options
author | Tyler Murphy <tylerm@tylerm.dev> | 2023-05-06 00:39:44 -0400 |
---|---|---|
committer | Tyler Murphy <tylerm@tylerm.dev> | 2023-05-06 00:39:44 -0400 |
commit | d8f2c10b7108fff6b7e437291093a1cadc15ab9f (patch) | |
tree | 3fc50a19d6fbb9c94a8fe147cd2a6c4ba7f59b8d /lib/file.c | |
parent | ansii c (diff) | |
download | lazysphere-d8f2c10b7108fff6b7e437291093a1cadc15ab9f.tar.gz lazysphere-d8f2c10b7108fff6b7e437291093a1cadc15ab9f.tar.bz2 lazysphere-d8f2c10b7108fff6b7e437291093a1cadc15ab9f.zip |
refactor
Diffstat (limited to '')
-rw-r--r-- | lib/file.c | 63 |
1 files changed, 63 insertions, 0 deletions
diff --git a/lib/file.c b/lib/file.c new file mode 100644 index 0000000..f89b489 --- /dev/null +++ b/lib/file.c @@ -0,0 +1,63 @@ +#include "file.h" +#include "error.h" +#include "convert.h" + +#include <paths.h> +#include <errno.h> +#include <stdlib.h> +#include <string.h> +#include <sys/stat.h> +#include <fcntl.h> + +FILE* get_file_s(const char* path, const char* type) { + struct stat s; + FILE* file; + + if (streql("-", path) && type[0] == 'r') { + clearerr(stdin); + fflush(stdin); + return stdin; + } + + if (lstat(path, &s) < 0) { + if (type[0] != 'r') goto read; + error_s("failed to read %s: %s", path, strerror(errno)); + return NULL; + } + + if (S_ISDIR(s.st_mode)) { + error_s("%s is a directory", path); + return NULL; + } + +read: + + file = fopen(path, type); + + if (file == NULL) { + error_s("failed to %s file %s: %s", type[0] == 'r' ? "read" : "write", path, strerror(errno)); + } + + return file; +} + +FILE* get_file(const char* path, const char* type) { + FILE* file = get_file_s(path, type); + if (file == NULL) exit(EXIT_FAILURE); + return file; +} + +int get_tty (void) { + int fd = open(_PATH_TTY, O_RDONLY); + if (fd < 0) error("failed to get tty: %s", strerror(errno)); + return fd; +} + +FILE* get_tty_stream(char* type) { + int fd = get_tty(); + FILE* file = fdopen(fd, type); + if (file == NULL) { + error("failed to open tty stream: %s", strerror(errno)); + } + return file; +} |