Fix bugs with io routines
diff --git a/include/io.h b/include/io.h
index 0b8a4b1..53c77d8 100644
--- a/include/io.h
+++ b/include/io.h
@@ -26,6 +26,8 @@
#include <stdio.h>
#include <stdlib.h>
+#include <bc.h>
+
typedef int (*BcIoGetc)(void*);
long bc_io_frag(char* buf, long len, int term, BcIoGetc bcgetc, void* ctx);
@@ -34,8 +36,10 @@
#define bc_io_gets(buf, n) bc_io_fgets((buf), (n), stdin)
-size_t bc_io_fgetline(char** p, size_t* n, FILE* fp);
+BcStatus bc_io_fgetline(char** p, size_t* n, FILE* fp);
#define bc_io_getline(p, n) bc_io_fgetline((p), (n), stdin)
+BcStatus bc_io_fread(const char* path, char** buf);
+
#endif // BC_IO_H
diff --git a/src/bc/io.c b/src/bc/io.c
index 9e2a5b1..54b31f2 100644
--- a/src/bc/io.c
+++ b/src/bc/io.c
@@ -70,13 +70,13 @@
return len;
}
-size_t bc_io_fgetline(char** p, size_t* n, FILE* fp) {
+BcStatus bc_io_fgetline(char** p, size_t* n, FILE* fp) {
size_t mlen, slen, dlen, len;
char* s;
char* t;
- if (!fp) return BC_INVALID_IDX;
+ if (!p || !n || !fp) return BC_STATUS_INVALID_PARAM;
if (!p) {
@@ -115,9 +115,56 @@
*p = s;
*n = slen;
- return slen;
+ return BC_STATUS_SUCCESS;
}
}
- return BC_INVALID_IDX;
+ return BC_STATUS_IO_ERR;
+}
+
+BcStatus bc_io_fread(const char* path, char** buf) {
+
+ BcStatus status;
+ FILE* f;
+ size_t size;
+ size_t read;
+
+ f = fopen(path, "r");
+
+ if (!f) return BC_STATUS_EXEC_FILE_ERR;
+
+ fseek(f, 0, SEEK_END);
+ size = ftell(f);
+
+ fseek(f, 0, SEEK_SET);
+
+ *buf = malloc(size + 1);
+
+ if (!*buf) {
+ status = BC_STATUS_MALLOC_FAIL;
+ goto malloc_err;
+ }
+
+ read = fread(*buf, 1, size, f);
+
+ if (read != size) {
+ status = BC_STATUS_IO_ERR;
+ goto read_err;
+ }
+
+ (*buf)[size] = '\0';
+
+ fclose(f);
+
+ return BC_STATUS_SUCCESS;
+
+read_err:
+
+ free(*buf);
+
+malloc_err:
+
+ fclose(f);
+
+ return status;
}
diff --git a/src/bc/program.c b/src/bc/program.c
index 11e98a9..38e628d 100644
--- a/src/bc/program.c
+++ b/src/bc/program.c
@@ -1341,10 +1341,9 @@
size = BC_PROGRAM_BUF_SIZE;
- if (bc_io_getline(&buffer, &size) == BC_INVALID_IDX) {
- status = BC_STATUS_IO_ERR;
- goto io_err;
- }
+ status = bc_io_getline(&buffer, &size);
+
+ if (status) goto io_err;
status = bc_parse_init(&parse, p);