-
Notifications
You must be signed in to change notification settings - Fork 5
/
echo.c
63 lines (52 loc) · 1.11 KB
/
echo.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
#include "types.h"
#include "stat.h"
#include "user.h"
/**
* Usage: echo [-n] [text...]
* Prints the input text to the stdout using the write system call.
* The command will insert a new line at the end of the text except if the -n switch
* is provided.
* Notes: It is important for text to be written in one write call to allow
* echo to interact with special kernel files such as for cgroups.
*/
int
main(int argc, char *argv[])
{
int i = 1;
int j = 0;
int size = 0;
char * data = 0;
int offset = 0;
char new_line = 1;
int result = 0;
if (argc > 1 && !strcmp("-n", argv[1])) {
++i;
new_line = 0;
}
for (j = i; j < argc; ++j) {
size += strlen(argv[j]) + 1;
}
data = malloc(size);
if (!data) {
exit(1);
}
for (; i < argc; ++i) {
int length = strlen(argv[i]);
memmove(data + offset, argv[i], length);
offset += length;
if (i + 1 < argc) {
data[offset] = ' ';
++offset;
}
}
if (new_line) {
data[offset] = '\n';
++offset;
}
result = write(1, data, offset);
free(data);
if (-1 == result) {
exit(1);
}
exit(0);
}