This repository has been archived by the owner on Nov 24, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathecho.c
150 lines (130 loc) · 2.36 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
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
#include "main.h"
/**
* _itoa - Entry point
* @value: integer to be converted
* Return: string converted from integer
*/
char *_itoa(int value)
{
int i, len = 0;
int temp = value;
char *str = (char *)malloc((len + 1) * sizeof(char));
while (temp != 0)
{
len++;
temp /= 10;
}
if (value == 0)
{
len = 1;
}
if (str == NULL)
{
return (NULL);
}
for (i = len - 1; i >= 0; i--)
{
str[i] = '0' + (value % 10);
value /= 10;
}
str[len] = '\0';
return (str);
}
/**
* my_echo - Entry point
* @args: command and arguments
* Return: Always 0 (Success)
*/
int my_echo(char **args)
{
int i, len;
int printed_chars = 0;
for (i = 1; args[i] != NULL && i < MAXARGS - 1; i++)
{
if (_strcmp(args[i], "$$") == 0)
{
echo_ppid(printed_chars);
}
else if (_strcmp(args[i], "$?") == 0)
{
echo_exit(printed_chars);
}
else if (args[i][0] == '$')
{
echo_env(printed_chars, args, i);
}
else
{
len = _strlen(args[i]);
printed_chars += write(STDOUT_FILENO, args[i], len);
printed_chars += len;
}
if (args[i + 1] != NULL)
{
printed_chars += write(STDOUT_FILENO, " ", 1);
printed_chars++;
}
}
return (printed_chars);
}
/**
* echo_ppid - Entry point
* @printed_chars: character count
* Return: Always 0 (Success)
*/
int echo_ppid(int printed_chars)
{
int len;
pid_t pid;
char *pid_str;
pid = getpid();
pid_str = _itoa(pid);
if (pid_str != NULL)
{
len = _strlen(pid_str);
printed_chars += write(STDOUT_FILENO, pid_str, len);
free(pid_str);
}
return (0);
}
/**
* echo_exit - Entry point
* @printed_chars: character count
* Return: Always 0 (Success)
*/
int echo_exit(int printed_chars)
{
int exit_status = exit_stat();
char *exit_status_str = _itoa(exit_status);
if (exit_status_str != NULL)
{
int len = _strlen(exit_status_str);
printed_chars += write(STDOUT_FILENO, exit_status_str, len);
free(exit_status_str);
}
return (0);
}
/**
* echo_env - Entry point
* @printed_chars: character count
* @args: arguments
* @i: iterate variable
* Return: Always 0 (Success)
*/
int echo_env(int printed_chars, char **args, int i)
{
int len;
char *value;
char *var_name;
var_name = args[i] + 1;
value = _getenv(var_name);
if (value != NULL)
{
len = _strlen(value);
printed_chars += write(STDOUT_FILENO, value, len);
printed_chars += len;
}
else
return (0);
return (0);
}