~ashn/cdoc

ref: 895edeebd33551540276a042fda9cef0911bd5b2 cdoc/cdoc.c -rw-r--r-- 1.8 KiB View raw
895edeebashn Creating a C Documentation Generator - Part 1 2 months ago
                                                                                
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
68
69
70
71
72
73
74
75
76
77
78
79
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define VERSION "0.0"

static void
usage(void);

static void
version(void);

static void
do_file(void);

static FILE* fp = NULL;

int
main(int argc, char** argv)
{
    bool parse_options = true;
    for (int i = 1; i < argc; ++i)
    {
        char const* const arg = argv[i];
        if (parse_options && strcmp(arg, "--help") == 0) { usage(); }
        if (parse_options && strcmp(arg, "--version") == 0) { version(); }
        if (parse_options && strcmp(arg, "--") == 0)
        {
            parse_options = false;
            continue;
        }

        fp = (strcmp(arg, "-") == 0 && !parse_options) ? stdin
                                                       : fopen(arg, "rb");
        if (fp == NULL)
        {
            perror(arg);
            exit(EXIT_FAILURE);
        }
        do_file();
        fclose(fp);
    }

    return EXIT_SUCCESS;
}

static void
usage(void)
{
    // clang-format off
    puts(
        "Usage: cdoc [OPTION]... [--] [FILE]..."                "\n"
                                                                "\n"
        "With no FILE, or when FILE is -, read standard input." "\n"
                                                                "\n"
        "Options:"                                              "\n"
        "  --help      Display usage information and exit."     "\n"
        "  --version   Display version information and exit."   "\n"
    );
    // clang-format on
    exit(EXIT_SUCCESS);
}

static void
version(void)
{
    puts(VERSION);
    exit(EXIT_SUCCESS);
}

// TODO: Change this function to implement file parsing and printing logic
// rather than just emulate `cat`.
static void
do_file(void)
{
    int c;
    while ((c = fgetc(fp)) != EOF) { fputc(c, stdout); }
}