forked from aamine/stdlinux2-source
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcat4.c
80 lines (71 loc) · 1.59 KB
/
cat4.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
/*
cat4.c -- simple cat command with -e option
Copyright (c) 2017 Minero Aoki
This program is free software.
Redistribution and use in source and binary forms,
with or without modification, are permitted.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
static void do_cat(FILE *f, int escape);
int
main(int argc, char *argv[])
{
int opt;
int escape = 0;
int i;
while ((opt = getopt(argc, argv, "e")) != -1) {
switch (opt) {
case 'e':
escape = 1;
break;
case '?':
fprintf(stderr, "Usage: %s [-e] [file...]\n", argv[0]);
exit(1);
}
}
argc -= optind;
argv += optind;
if (argc == 0) {
do_cat(stdin, escape);
}
else {
for (i = 0; i < argc; i++) {
FILE *f;
f = fopen(argv[i], "r");
if (!f) {
perror(argv[i]);
exit(1);
}
do_cat(f, escape);
fclose(f);
}
}
exit(0);
}
static void
do_cat(FILE *f, int escape)
{
int c;
if (escape) {
while ((c = fgetc(f)) != EOF) {
switch (c) {
case '\t':
if (fputs("\\t", stdout) == EOF) exit(1);
break;
case '\n':
if (fputs("$\n", stdout) == EOF) exit(1);
break;
default:
if (putchar(c) < 0) exit(1);
break;
}
}
}
else {
while ((c = fgetc(f)) != EOF) {
if (putchar(c) < 0) exit(1);
}
}
}