lazysphere/lib/file.c

62 lines
1.2 KiB
C
Raw Normal View History

2023-05-15 01:43:02 +00:00
#include "lslib.h"
2023-05-06 04:39:44 +00:00
#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;
2023-05-15 01:43:02 +00:00
error_s("failed to read %s", path);
2023-05-06 04:39:44 +00:00
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) {
2023-05-15 01:43:02 +00:00
error_s("failed to %s file %s", type[0] == 'r' ? "read" : "write", path);
2023-05-06 04:39:44 +00:00
}
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) {
2023-05-15 01:43:02 +00:00
int fd = open(_PATH_TTY, O_RDONLY | O_NOCTTY | O_SYNC);
if (fd < 0) error("failed to get tty");
2023-05-06 04:39:44 +00:00
return fd;
}
FILE* get_tty_stream(char* type) {
int fd = get_tty();
FILE* file = fdopen(fd, type);
if (file == NULL) {
2023-05-15 01:43:02 +00:00
error("failed to open tty stream");
2023-05-06 04:39:44 +00:00
}
return file;
}