-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcatmd.c
84 lines (71 loc) · 1.68 KB
/
catmd.c
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
80
81
82
83
84
#include <ctype.h>
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <wchar.h>
#include <wctype.h>
#if !defined(VERSION)
#define VERSION "unknown"
#endif // VERSION
void print_usage() {
printf("Usage: catmd [options] <file ...>\n\n");
printf("Options:\n");
printf(" -h, --help output usage information\n");
printf(" -v, --version output the version number\n");
}
void catmd(const char* filename) {
FILE* fp = fopen(filename, "r");
if (fp == NULL) {
perror(filename);
return;
}
wprintf(L"*%s*\n\n", filename);
const char* extension = strrchr(filename, '.');
if (extension != NULL) {
wprintf(L"```%s\n", extension + 1);
} else {
wprintf(L"```text\n");
}
wint_t ch;
while ((ch = fgetwc(fp)) != WEOF) {
if (iswprint(ch) || ch == L'\n' || ch == L'\t') {
putwchar(ch);
} else {
wprintf(L"\\x%02x", ch);
}
}
fclose(fp);
if (ch != L'\n') {
putwchar(L'\n');
}
wprintf(L"```\n\n");
}
int main(int argc, char* argv[]) {
int opt;
static struct option long_options[] = {{"help", no_argument, 0, 'h'},
{"version", no_argument, 0, 'v'},
{0, 0, 0, 0}};
while ((opt = getopt_long(argc, argv, "hv", long_options, NULL)) != -1) {
switch (opt) {
case 'h':
print_usage();
exit(0);
case 'v':
printf("catmd version %s\n", VERSION);
exit(0);
default:
print_usage();
exit(1);
}
}
if (optind >= argc) {
print_usage();
exit(1);
}
for (int i = optind; i < argc; i++) {
catmd(argv[i]);
}
return 0;
}