чување 19ced272d9e06c3d24516f0d3e9104c7553f83cb
родитељ 48bda8f4e48cd895be313ac0b4800059a0648f30
Аутор: Страхиња Радић <contact@strahinja.org>
Датум: Sun, 13 Feb 2022 01:32:14 +0100
sled.c: Improve file testing
Signed-off-by: Страхиња Радић <contact@strahinja.org>
Diffstat:
| M | sled.c | | | 34 | +++++++++++++++++++++------------- |
измењених датотека: 1, додавања: 21(+), брисања: 13(-)
diff --git a/sled.c b/sled.c
@@ -3,12 +3,15 @@
#define _POSIX_C_SOURCE 200809L
#include <errno.h>
+#include <fcntl.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
+#include <sys/stat.h>
#include <time.h>
+#include <unistd.h>
#include "version.h"
#include "termbox.h"
@@ -279,25 +282,24 @@ load_file(struct DrawState* dstate, long* lineno, long* col)
{
struct BufferLine* newchunk
= calloc(ALLOC_DELTA, sizeof(struct BufferLine));
- struct BufferLine* line = NULL;
- struct BufferLine* current = NULL;
- FILE* input = NULL;
+ struct BufferLine* line = NULL;
+ FILE* input = NULL;
char input_line[MAXBUFLINE];
if (!newchunk)
return LOAD_ERR_CANT_ALLOC;
- dstate->buffer = newchunk;
- line = dstate->buffer;
+ dstate->buffer = newchunk;
+ line = dstate->buffer;
dstate->buffer_size = ALLOC_DELTA;
- dstate->rows_count = 0;
+ dstate->rows_count = 0;
if (!(input = fopen(dstate->filename, "rt")))
return LOAD_ERR_CANT_OPEN_FILE;
while (!feof(input))
{
- char* eol = NULL;
+ char* eol = NULL;
uint32_t* newtext = NULL;
if (!fgets(input_line, MAXBUFLINE, input))
@@ -322,7 +324,7 @@ load_file(struct DrawState* dstate, long* lineno, long* col)
newtext = calloc(MAXBUFLINE, sizeof(uint32_t));
if (!newtext)
return LOAD_ERR_CANT_ALLOC;
- line->text = newtext;
+ line->text = newtext;
line->length = u32_u8_strcpy(line->text, input_line);
dstate->rows_count++;
}
@@ -1478,8 +1480,8 @@ main(int argc, char** argv)
char error[MAXBUFLINE];
char prompt[MAXBUFLINE];
struct DrawState state;
- FILE* input = NULL;
char filename[MAXPATH];
+ struct stat st;
error[0] = 0;
prompt[0] = 0;
@@ -1500,9 +1502,15 @@ main(int argc, char** argv)
return print_error(EINVAL, "No filename given");
}
- if (!(input = fopen(filename, "rt")))
- return print_error(ENOENT, "No such file `%s'", filename);
- fclose(input);
+ if (stat(filename, &st) == -1
+ || access(filename, F_OK | R_OK | W_OK) == -1)
+ {
+ perror(program_name);
+ return errno;
+ }
+
+ if (!S_ISREG(st.st_mode))
+ return print_error(EINVAL, "Is not a regular file");
init_drawstate(&state, error, filename, prompt);
@@ -1516,7 +1524,7 @@ main(int argc, char** argv)
case LOAD_ERR_CANT_OPEN_FILE:
return print_error(result, "Cannot open file `%s'", filename);
case LOAD_ERR_NONE:
- if (error[0] != 0)
+ if (*error)
return print_error(1, error);
break;
default: