aboutsummaryrefslogtreecommitdiff
path: root/src/source.c
blob: f7f7063f1b1c249d223d8f9a8e8d82f9b59d66ea (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include "include/source.h"
#include <unistd.h>
char* source_get(char* arg) {
   return arg? 
      source_get_from_fpath(arg):
      source_get_from_stdin();
}

char* source_get_from_fpath(char* path) {
   FILE* f;
   long f_size;
   char* src;

   f = fopen(path, "rb");
   if (!f) { die("source file not found: %s", path); }

   fseek(f, 0L, SEEK_END);
   f_size = ftell(f);
   rewind(f);

   src = ecalloc(1, f_size + 1);

   if ((fread(src, f_size, 1, f) != 1) || !src) {
      fclose(f);
      free(src);
      die("could not read source file: %s", path);
   }

   return src;
}

char* source_get_from_stdin() {
   char* src;
   size_t l;

   src = ecalloc(256, sizeof(char));
   l = 0;

   while (fgets(src + l, 20, stdin) != NULL) {
      l += strlen(src + l);
   }

   (src[l - 1] == '\n') && (src[l - 1] = '\0');

//   src = fgets(src, 256, stdin);

   return src;
}