option for output file

Wed, 10 Jul 2013 13:38:28 +0200

author
Mike Becker <universe@uap-core.de>
date
Wed, 10 Jul 2013 13:38:28 +0200
changeset 11
c59fe73459fd
parent 6
d10f7570add4
child 12
7ce5c4b51959

option for output file

src/c2html.c file | annotate | diff | comparison | revisions
--- a/src/c2html.c	Wed Jun 12 14:50:27 2013 +0200
+++ b/src/c2html.c	Wed Jul 10 13:38:28 2013 +0200
@@ -44,6 +44,10 @@
   "switch", "typedef", "union", "unsigned", "void", "volatile", "while", NULL
 };
 
+typedef struct {
+  char* outfilename;
+  char* infilename;
+} settings_t;
 
 typedef struct {
   size_t count;
@@ -204,7 +208,10 @@
 
 void printhelp() {
   printf("Formats source code using HTML.\n\nUsage:\n"
-      "  c2html [FILE...]"
+      "  c2html [Options] FILE\n\n"
+      " Options:\n"
+      "  -h                    Prints this help message\n"
+      "  -o <output>           Output file (if not specified, stdout is used)\n"
       "\n");
   
   
@@ -218,23 +225,54 @@
 
 int main(int argc, char** argv) {
   
-  if (argc == 1) {
+  settings_t settings;
+  settings.outfilename = NULL;
+  
+  char optc;
+  while ((optc = getopt(argc, argv, "ho:")) != -1) {
+    switch (optc) {
+      case 'o':
+        if (!(optarg[0] == '-' && optarg[1] == 0)) {
+          settings.outfilename = optarg;
+        }
+        break;
+      case 'h':
+        printhelp();
+        return 0;
+      default:
+        return 1;
+    }
+  }
+
+  if (optind != argc-1) {
     printhelp();
-    return 0;
+    return 1;
   } else {
+    settings.infilename = argv[optind];
     
-    inputfile_t *inputfile = readinput(argv[1]);
+    inputfile_t *inputfile = readinput(settings.infilename);
     if (inputfile) {
-      printf("<pre>\n");
+      FILE *fout;
+      if (settings.outfilename) {
+        fout = fopen(settings.outfilename, "w");
+      } else {
+        fout = stdout;
+      }
+      fprintf(fout, "<pre>\n");
       char *line = (char*) malloc(inputfile->maxlinewidth*64);
       int lnw = lnint(inputfile->count);
       for (int i = 0 ; i < inputfile->count ; i++) {
         parseline(inputfile->lines[i], line);
-        printf("<span class=\"c2html-lineno\">%*d:</span> %s",
+        fprintf(fout, "<span class=\"c2html-lineno\">%*d:</span> %s",
             lnw, i, line);
       }
       free(line);
-      printf("</pre>\n");
+      fprintf(fout, "</pre>\n");
+      
+      if (fout != stdout) {
+        fclose(fout);
+      }
+      
       freeinputfilebuffer(inputfile);
     }
   

mercurial