-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.c
67 lines (54 loc) · 1.32 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
67
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include "utils.h"
#define MAX_FILENAMESIZE 64
#define MAX_LINELENGTH 80
#define BIN_STRING_LENGTH 17
int main(int argc, char **argv)
{
char output_file[MAX_FILENAMESIZE], instr[MAX_LINELENGTH],
bin[BIN_STRING_LENGTH];
FILE *readptr, *writeptr;
if (argc < 2)
{
fprintf(stderr, "Error: Program requires at least one input\
filename argument.\nUsage: '%s <file>'\n",
argv[0]);
return -1;
}
readptr = fopen(argv[1], "r");
if (readptr == NULL)
{
fprintf(stderr, "Error: %s\n", strerror(errno));
return -1;
}
// if no filename argument, default to "out.hack"
if (argv[2] == NULL)
{
sprintf(output_file, "out.hack");
}
else
{
sprintf(output_file, "%s", argv[2]);
}
writeptr = fopen(output_file, "w");
while (fgets(instr, sizeof instr, readptr) != NULL)
{
trim_instruction(instr);
if (*instr == '\n')
continue;
if (*instr == '@')
{
assemble_a_instruction(instr, bin);
}
else
{
assemble_c_instruction(instr, bin);
}
fprintf(writeptr, "%s", bin);
}
fclose(readptr);
fclose(writeptr);
return 0;
}