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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
|
#define _POSIX_C_SOURCE 200809L
#include <err.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "IO/IOBackend.h"
#include "utils/env.h"
static void _usage_xerror(void)
{
errx(2, "Usage:\n\
\t./42sh [--pretty-print] [FILENAME]\n\
\t./42sh [-c | --pretty-print] [FILENAME]\n\
\t./42sh [--pretty-print] [ < FILENAME ]");
}
static struct string *_parse_input(FILE *f)
{
ssize_t r = 0;
struct string *output = string_create(NULL);
char buf[DEFAULT_RW_SIZE + 1] = { 0 };
do
{
r = fread(buf, sizeof(char), DEFAULT_RW_SIZE, f);
if (r == -1)
{
fprintf(stderr, "_parse_input: fread failed!");
return NULL;
}
buf[r] = 0;
string_pushstr(output, buf);
} while (r >= DEFAULT_RW_SIZE);
return output;
}
static void _add_newline(struct string *s)
{
if (s->data[s->length - 1] != '\n')
{
string_pushc(s, '\n');
}
}
struct string *get_input(int argc, char *argv[])
{
int i = 1;
bool s_input = false;
FILE *f = NULL;
while (i < argc && argv[i][0] == '-')
{
if (strcmp(argv[i], "-c") == 0)
{
s_input = true;
i++;
continue;
}
if (strcmp(argv[i], "--pretty-print") == 0)
{
env_set("PRETTY_PRINT", "TRUE");
i++;
continue;
}
_usage_xerror();
}
if (i == argc)
{
f = stdin;
}
else
{
char *input = argv[i];
if (s_input)
{
f = fmemopen(input, strlen(input) + 1, "r");
}
else
{
f = fopen(input, "r");
env_set("0", input);
}
}
if (!f)
{
errx(2, "Invalid path!");
}
struct string *string_input = _parse_input(f);
if (f != stdin)
{
fclose(f);
}
int nb_args = 0;
i++;
for (; i < argc; i++)
{
nb_args++;
char buf[16] = { 0 };
sprintf(buf, "%d", nb_args);
env_set(buf, argv[i]);
}
char buf2[16] = { 0 };
sprintf(buf2, "%d", (s_input && nb_args > 0) ? 1 : nb_args);
env_set("#", buf2);
_add_newline(string_input);
return string_input;
}
|