aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorRaghuram Subramani <raghus2247@gmail.com>2025-06-08 13:33:58 +0530
committerRaghuram Subramani <raghus2247@gmail.com>2025-06-08 13:33:58 +0530
commit1de0b57e396d1964aba2c8ddc663bd55d01f5058 (patch)
treeccc6fe94ca738136e3da27cd4ff0fbfd230c3ee7 /src
parent25d651a1a4100be0d7b148030d8e3bca6996f53b (diff)
filehandler: init
Diffstat (limited to 'src')
-rw-r--r--src/filehandler.cc55
-rw-r--r--src/main.cc22
-rw-r--r--src/scanner.cc2
3 files changed, 62 insertions, 17 deletions
diff --git a/src/filehandler.cc b/src/filehandler.cc
new file mode 100644
index 0000000..a901fc5
--- /dev/null
+++ b/src/filehandler.cc
@@ -0,0 +1,55 @@
+#include <filehandler.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+Filehandler::Filehandler(char *path)
+{
+ f = NULL;
+ buffer = NULL;
+ this->path = path;
+}
+
+bool
+Filehandler::open(void)
+{
+ f = fopen(path, "r");
+ if (f == NULL) {
+ printf("Unable to open %s\n", path);
+ return false;
+ }
+
+ return true;
+}
+
+unsigned int
+Filehandler::size(void)
+{
+ unsigned int current = ftell(f);
+
+ fseek(f, 0, SEEK_END);
+ unsigned int s = ftell(f);
+
+ fseek(f, current, SEEK_SET);
+ return s;
+}
+
+char *
+Filehandler::read(void)
+{
+ fseek(f, 0, SEEK_SET);
+
+ buffer = (char *) calloc(size(), sizeof(char));
+ int bytesread = fread(buffer, sizeof(char), size(), f);
+
+ if (bytesread < 0) {
+ return NULL;
+ }
+ return buffer;
+}
+
+void
+Filehandler::close(void)
+{
+ fclose(f);
+ free(buffer);
+}
diff --git a/src/main.cc b/src/main.cc
index d357756..ea28324 100644
--- a/src/main.cc
+++ b/src/main.cc
@@ -1,3 +1,4 @@
+#include <filehandler.h>
#include <scanner.h>
#include <stdio.h>
#include <stdlib.h>
@@ -5,34 +6,23 @@
int
main(int argc, char **argv)
{
- (void) argc;
- (void) argv;
-
if (argc != 2) {
printf("Usage: %s <script>\n", argv[0]);
return 1;
}
- FILE *f = fopen(argv[1], "r");
- if (f == NULL) {
+ Filehandler f(argv[1]);
+ bool success = f.open();
+ if (!success) {
printf("Unable to open %s\n", argv[1]);
return 1;
}
- fseek(f, 0, SEEK_END);
- unsigned long fsize = ftell(f);
- fseek(f, 0, SEEK_SET);
-
- char *buffer = (char *) calloc(fsize, sizeof(char));
- int bytesread = fread(buffer, sizeof(char), fsize, f);
- if (bytesread < 0) {
- printf("Unable to open %s\n", argv[1]);
- return 1;
- }
+ char *buffer = f.read();
Scanner s(buffer);
s.scan_tokens();
- free(buffer);
+ f.close();
return 0;
}
diff --git a/src/scanner.cc b/src/scanner.cc
index f193562..cff7676 100644
--- a/src/scanner.cc
+++ b/src/scanner.cc
@@ -1,5 +1,5 @@
-#include <cstdio>
#include <scanner.h>
+#include <stdio.h>
Scanner::Scanner(char *script) : script(script) {}