-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsx_head.c
135 lines (91 loc) · 1.63 KB
/
sx_head.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
/* sx_head.c
HEAD for SamaruX.
Print first lines from files.
Copyright (c) 2016 Miguel Garcia / FloppySoftware.
Usage:
head [-nNUMBER] [file ...]
Options:
-nNUMBER: Print n lines.
Examples:
head -n6 myletter.doc resume.txt
head calendar.txt
Changes:
06 Jun 2016 : v1.00 : Built-in and external.
*/
/* Built-in or external
--------------------
*/
#ifdef SX_SAMARUX
#define SX_HEAD
#else
#include "samarux.h"
#define HeadMain main
#endif
HeadMain(argc, argv)
int argc, argv[];
{
char *pch;
int lines, i, retcode, argx;
/* Default values */
lines = 10; /* Print # lines */
/* Parse command line arguments */
for(i = 1; i < argc; ++i)
{
pch = argv[i];
if(*pch == '-') /* Look for -options */
{
if(*(++pch) == 'n')
{
lines = atoi(++pch);
if(lines < 1 || lines > 32000)
return Error("Bad # of lines");
}
else
return ErrorOpt();
}
else /* Look for files */
break;
}
argx = i;
/* Process files */
if(argx == argc)
retcode = HeadOut("-", lines);
else
{
while(argx < argc)
{
if((retcode = HeadOut(argv[argx++], lines)))
break;
}
}
/* Success or failure */
return retcode;
}
HeadOut(fn, lines)
char *fn; int lines;
{
FILE *fp;
int ch;
/* Open the file */
if(fn[0] == '-' && fn[1] == 0)
fp = stdin;
else if((fp = fopen(fn, "r")) == NULL)
return ErrorOpen();
/* Read and print the lines */
while(lines) {
/* Read char. */
ch = fgetc(fp);
/* EOL ? */
if(ch == '\n')
--lines;
else if(ch == EOF)
break;
/* Print char. */
putchar(ch);
}
/* Close the file */
if(fp != stdin)
fclose(fp);
/* Success */
return 0;
}