чување 8092bda4912d934f334c54890d54e2e7a6c08121
родитељ 1c14678b78602af91a33a9edf2ebfe7369aa22ca
Аутор: Страхиња Радић <sr@strahinja.org>
Датум: Wed, 10 Jul 2024 15:00:28 +0200
dtree.c: Tidy up error messages; check if file is a regular file
Diffstat:
| M | TODO | | | 2 | +- |
| M | dtree.c | | | 30 | ++++++++++++++++++++---------- |
измењених датотека: 2, додавања: 21(+), брисања: 11(-)
diff --git a/TODO b/TODO
@@ -1,4 +1,4 @@
TODO
====
-[ ] Check if argument is a file or something else
+[x] Check if argument is a file or something else
diff --git a/dtree.c b/dtree.c
@@ -12,6 +12,7 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
+#include <sys/stat.h>
#include <unistd.h>
#include "utf8.h"
@@ -89,7 +90,7 @@ alloc_node(void)
if (!newnode)
{
perror(PROGRAMNAME ": malloc");
- exit(1);
+ exit(errno);
}
assert(newnode != NULL);
@@ -275,7 +276,7 @@ set_node(struct Node* node, const int level, const char* label)
if (!node->label)
{
perror(PROGRAMNAME ": malloc");
- exit(1);
+ exit(errno);
}
}
if (!memccpy(node->label, label, 0, size))
@@ -313,6 +314,7 @@ warning(const char* fmt, ...)
int
main(int argc, char** argv)
{
+ struct stat st;
FILE* input = NULL;
char* line = NULL;
char* pline = NULL;
@@ -327,7 +329,7 @@ main(int argc, char** argv)
if (pledge("stdio rpath unveil", NULL) < 0)
{
perror(PROGRAMNAME ": pledge");
- exit(1);
+ exit(errno);
}
#endif
@@ -371,18 +373,26 @@ main(int argc, char** argv)
if (unveil(argv[optind], "r") < 0)
{
perror(PROGRAMNAME ": unveil");
- exit(1);
+ exit(errno);
}
if (unveil(NULL, NULL) < 0)
{
perror(PROGRAMNAME ": unveil");
- exit(1);
+ exit(errno);
}
#endif
+ if (stat(argv[optind], &st) < 0)
+ {
+ perror(PROGRAMNAME ": stat");
+ exit(errno);
+ }
+ if (!S_ISREG(st.st_mode))
+ exit(error(EINVAL, "Is not a regular file"));
+
if (!(input = fopen(argv[optind], "r")))
{
perror(PROGRAMNAME ": fopen");
- exit(error(1, "Can't open '%s'", argv[optind]));
+ exit(errno);
}
}
@@ -392,8 +402,8 @@ main(int argc, char** argv)
{
if (errno)
{
- perror("sysconf");
- exit(1);
+ perror(PROGRAMNAME ": sysconf");
+ exit(errno);
}
line_delta = _POSIX2_LINE_MAX;
}
@@ -416,7 +426,7 @@ do_input:
if (!(tpline = realloc(line, line_size)))
{
perror(PROGRAMNAME ": realloc");
- exit(1);
+ exit(errno);
}
line = tpline;
pline = line + (line_size - line_delta - 1);
@@ -455,7 +465,7 @@ done_input:
if (!indent)
{
perror(PROGRAMNAME ": calloc");
- exit(1);
+ exit(errno);
}
pindent = indent;