main.c (2642B)
1 #include <stdio.h> 2 #include <stdint.h> 3 #include <stdlib.h> 4 #include <string.h> 5 #include <unistd.h> 6 7 typedef uint8_t u8; 8 typedef uint32_t u32; 9 typedef int8_t i8; 10 typedef int32_t i32; 11 12 #define DIE(str) do { \ 13 fprintf(stderr, "ERROR in line %d: %s\n", __LINE__, str); \ 14 exit(EXIT_FAILURE); \ 15 } while (0); 16 17 typedef enum { 18 CMD_BOLD, CMD_ITALIC, CMD_H1, CMD_H2, CMD_HTML 19 } CMD_TYPE; 20 21 const char opening_tags[20][20] = { 22 {"<b>"}, {"<i>"}, {"<h1>"}, {"<h2>"}, {"<html>"} 23 }; 24 25 const char closing_tags[20][20] = { 26 {"</b>"}, {"</i>"}, {"</h1>"}, {"</h2>"}, {"</html>"} 27 }; 28 29 typedef struct { 30 i8 top; 31 CMD_TYPE arr[100]; 32 } stack; 33 34 stack stack_init(void) { stack s; s.top = -1; return s; } 35 void stack_push(stack *s, CMD_TYPE val) { s->arr[++s->top] = val; return; } 36 CMD_TYPE stack_pop(stack *s) { return s->arr[s->top--]; } 37 CMD_TYPE stack_peek(stack *s) { return s->arr[s->top]; } 38 39 char* 40 file_open(const char* flname) 41 { 42 FILE* fp; 43 long sz; 44 char *file; 45 46 if (flname == NULL) DIE("No file Given"); 47 48 fp = fopen(flname, "rb"); 49 50 if (fp == NULL) DIE("Opening the file"); 51 52 fseek(fp, 0, SEEK_END); 53 sz = ftell(fp); 54 rewind(fp); 55 56 file = malloc(sizeof(u8)*sz); 57 58 fread(file, sz, 1, fp); 59 fclose(fp); 60 61 return file; 62 } 63 64 i32 65 cmd_get(const char* cmd) 66 { 67 if (strcmp(cmd, "~b") == 0) return CMD_BOLD; 68 if (strcmp(cmd, "~h1") == 0) return CMD_H1; 69 if (strcmp(cmd, "~h2") == 0) return CMD_H2; 70 if (strcmp(cmd, "~i") == 0) return CMD_ITALIC; 71 if (strcmp(cmd, "~html") == 0) return CMD_HTML; 72 return -2; 73 } 74 75 void 76 parse_cmd(char* cur) 77 { 78 79 } 80 81 int 82 main(int argc, char **argv) 83 { 84 char *in; 85 char *out; 86 FILE *fp_out; 87 char *cur; 88 char *looker; 89 char token[20]; 90 91 stack s = stack_init(); 92 93 in = file_open("test.txt"); 94 fp_out = fopen("index.html", "w"); 95 96 cur = &in[0]; 97 98 while (*cur != '\0') { 99 if (*cur == '~') { 100 looker = cur; 101 102 while (*(++looker) >= '0' && *(looker) <= 'z'); 103 104 /* When it's just ~ */ 105 if (looker - cur == 1) { 106 const char* ch = closing_tags[stack_pop(&s)]; 107 fprintf(fp_out, "%s", ch); 108 } else { 109 /* So the token here is (cur) - (looker - cur) */ 110 sprintf(token, "%.*s", (int)(looker-cur), cur); 111 112 const char *cmd = opening_tags[cmd_get(token)]; 113 fprintf(fp_out, "%s", cmd); 114 115 stack_push(&s, cmd_get(token)); 116 } 117 118 cur = looker; 119 } else { 120 fputc(*cur++, fp_out); 121 } 122 } 123 124 free(in); 125 fclose(fp_out); 126 127 return 0; 128 }