|
CS456 - Systems Programming
| Displaying exercises/e6/files/main.c
#include "lex.h"
#define BUFSIZE 64*1024
char *tstring[] = {
"string", "number", "[", "]", "{", "}", ",", ":", "true", "false", "null",
"EOI", "?"
};
char *readfile(char *path)
{
int fd = open(path, O_RDONLY);
if (fd < 0) {
perror("open");
return NULL;
}
struct stat st;
if (fstat(fd, &st) < 0) {
perror("stat");
return NULL;
}
char *data = malloc(st.st_size+1);
size_t r;
if ((r = read(fd, data, st.st_size)) != st.st_size) {
printf("Short read, returned = %ld, expected = %ld\n", r, st.st_size);
free(data);
return NULL;
}
data[st.st_size] = '\0';
close(fd);
return data;
}
/**
* This program is not for you to modify. It is used for testing your lexer
* library. Use 'make test' to compile this program against your lexer and
* test it.
*/
int main(int argc, char *argv[])
{
if (argc < 2) {
printf("Usage: %s <file>\n", argv[0]);
return 1;
}
char *filedata = readfile(argv[1]);
if (filedata == NULL) return 1;
token_t tok;
char wbuf[BUFSIZE];
startlex(filedata);
while((tok = lex(wbuf)) != T_EOI) {
switch(tok) {
case T_STRING:
case T_NUMBER:
printf("%s: %s\n", tstring[tok], wbuf);
break;
default:
printf("token: %s\n", tstring[tok]);
break;
}
}
return 0;
}
|