-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.c
executable file
·66 lines (55 loc) · 1.53 KB
/
main.c
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
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
size_t get_argv_size(int argc, char **argv);
char *get_expression(int argc, char **argv);
char *get_exec_cmd(char *expression);
size_t get_argv_size(int argc, char **argv) {
size_t expression_size = strlen(argv[1]);
for (int i = 2; i < argc; i++) {
expression_size += strlen(argv[i]);
}
return expression_size;
}
char *get_expression(int argc, char **argv) {
char *cmd = malloc(get_argv_size(argc, argv));
for (int i = 1; i < argc; ++i) {
if (!strlen(cmd)) {
strcpy(cmd, argv[i]);
} else {
strcat(cmd, argv[i]);
}
}
return cmd;
}
char *get_exec_cmd(char *expression) {
char *format = "printf '0x%%x\n' $[%s]";
char *exec_cmd = malloc(strlen(expression) + strlen(format));
sprintf(exec_cmd, format, expression);
return exec_cmd;
}
int main (int argc, char **argv) {
if (argc < 2) {
printf("Usage - `hexcalc {expression}`\n");
return 0;
}
FILE *fp;
int status;
char path[1024];
char *expression = get_expression(argc, argv);
printf("evaling: %s\n", expression);
char *exec_cmd = get_exec_cmd(expression);
fp = popen(exec_cmd, "r");
if (fp == NULL) {
printf("Failed to run command\n" );
return 1;
}
while (fgets(path, sizeof(path) - 1, fp) != NULL) {
printf("result : %s", path);
}
free(expression);
free(exec_cmd);
pclose(fp);
return 0;
}