txt2html.c (2469B)
1 #include "txt2html.h" 2 3 struct node *convf(FILE *f); 4 int readn(struct node *n); 5 6 static uint8_t opts; // make extern if passing it about becomes a pain 7 8 void help() 9 { 10 puts("usage: txt2html [OPTIONS] FILE..."); 11 puts(""); 12 puts("Convert content in txt files to html."); 13 puts(""); 14 puts("FILE... A list of filepaths that point to files to be converted to HTML"); 15 puts(""); 16 puts("OPTIONS"); 17 puts("-br Treat newlines within paragraphs as line breaks."); 18 puts("-v Print verbose logs during runtime"); 19 puts("-h, --help Print this message"); 20 } 21 22 void verbose(const char *fmt, ...) 23 { 24 if (opts & OPT_V) { 25 printf("txt2html: "); 26 va_list args; 27 va_start(args, fmt); 28 vprintf(fmt, args); 29 va_end(args); 30 fflush(stdout); 31 } 32 } 33 34 void parseargs(int argc, char **argv) 35 { 36 int i = 0, a = argc-1; 37 for (; a > 0; --a) { 38 if (argv[a] == NULL) 39 continue; 40 if (argv[a][i] == '-') { 41 if (strcmp(argv[a], "-h") == 0 || 42 strcmp(argv[a], "--help") == 0) { 43 help(); 44 exit(0); 45 } else if (strcmp(argv[a], "-br") == 0) { 46 opts |= OPT_BR; 47 } else if (strcmp(argv[a], "-v") == 0) { 48 opts |= OPT_V; 49 } else if (strcmp(argv[a], "-nm") == 0) { 50 opts |= OPT_NM; 51 } 52 53 argv[a][0] = '\0'; 54 } 55 } 56 } 57 58 int main(int argc, char **argv) 59 { 60 parseargs(argc, argv); 61 verbose("printing verbose logs\n"); 62 63 int a; 64 FILE *f; 65 struct node *n; 66 for (a = 1; a < argc; ++a) { 67 if (strlen(argv[a]) == 0) 68 continue; 69 70 verbose("opening %s\n", argv[a]); 71 if ((f = fopen(argv[a], "r")) == NULL) { 72 perror("fopen failed, abort"); 73 continue; 74 } 75 76 n = convf(f); 77 verbose("counted %d nodes\n", readn(n)); 78 verbose("closing %s\n", argv[a]); 79 if (fclose(f) == EOF) perror("fclose failed"); 80 81 while (!n) { 82 if (n->buf && n->buf[strlen(n->buf)+1] == '$') 83 free(n->buf); 84 if (n->next) free(n->next); 85 if (n->prev) { 86 n = n->prev; 87 } else { 88 free(n); 89 break; 90 } 91 } 92 node_create(NULL, 0); // reset node count 93 } 94 95 return EXIT_SUCCESS; 96 } 97 98 struct node *convf(FILE *f) 99 { 100 int siz; 101 struct node *n = 0; 102 char buf[BUFSIZ] = {'\0'}; 103 while (true) { 104 siz = fread(buf, sizeof(char), BUFSIZ-1, f); 105 if (siz == 0) break; 106 buf[siz+1] = '\0'; 107 verbose("read %d bytes\n", siz); 108 n = parse_buf(buf, &n, opts); 109 } 110 n = parse_buf(NULL, &n, opts); 111 return n; 112 } 113 114 int readn(struct node *n) 115 { 116 while (n->prev) 117 n = n->prev; // rewind 118 int cnt = 0; 119 while (n) { 120 if (n->buf) printf("%s", n->buf); 121 n = n->next; 122 ++cnt; 123 } 124 return cnt; 125 }