-
Notifications
You must be signed in to change notification settings - Fork 12
/
unix10-cat.c
69 lines (64 loc) · 1.21 KB
/
unix10-cat.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
/*
* Concatenate files.
*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#define BLOCK 4096
char buf[BLOCK];
main (argc, argv)
int argc;
char **argv;
{
register int fflg = 0;
register int fi, fo;
register int n;
register int dev, ino = -1;
struct stat statb;
int retcode=0;
if (fstat (1, &statb) < 0) {
perror ("cat stdout");
return 1;
}
statb.st_mode &= S_IFMT;
/*
* st_nlink == 0 for pipes and other magic files
*/
if (statb.st_nlink!=0 && statb.st_mode!=S_IFCHR && statb.st_mode!=S_IFBLK) {
dev = statb.st_dev;
ino = statb.st_ino;
}
if (argc < 2) {
argc = 2;
fflg++;
}
while (--argc > 0) {
if (fflg || **++argv == '-' && (*argv)[1] == '\0')
fi = 0;
else {
if ((fi = open (*argv, 0)) < 0) {
fprintf(stderr, "cat: ");
perror (*argv);
retcode = 1;
continue;
}
}
if (fstat (fi, &statb) >= 0
&& statb.st_dev == dev
&& statb.st_ino == ino) {
fprintf (stderr, "cat: input %s is output\n",
fflg? "-": *argv);
close (fi);
retcode = 1;
continue;
}
while ((n = read (fi, buf, sizeof buf)) > 0)
if (write (1, buf, n) != n){
perror ("cat output");
return 1;
}
if (fi != 0)
close (fi);
}
return retcode;
}