Skip to content
This repository was archived by the owner on Dec 25, 2018. It is now read-only.

Commit 5f87500

Browse files
committed
correct impl: find, echo
1 parent f4e41fd commit 5f87500

File tree

1 file changed

+16
-12
lines changed

1 file changed

+16
-12
lines changed

builtin.c

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -46,8 +46,10 @@ int error_handler() {
4646
}
4747

4848
int set_euid_egid(int euid, int egid) {
49-
if (setegid(egid) == -1) return error_handler() - 1;
50-
if (seteuid(euid) == -1) return error_handler() - 1;
49+
if (setegid(egid) == -1 || seteuid(euid) == -1) {
50+
error_handler();
51+
return -1;
52+
}
5153
return 0;
5254
}
5355

@@ -117,7 +119,7 @@ int builtin_echo(char *line) {
117119
if (argc == 2) {
118120
FILE *file = fopen(filename, "a+");
119121
if (file == NULL) return error_handler();
120-
fprintf(file, "%s", arg);
122+
fprintf(file, "%s\n", arg);
121123
fclose(file);
122124
} else
123125
printf("%s\n", arg);
@@ -136,19 +138,22 @@ int builtin_find(char *line) {
136138
int argc;
137139
if ((argc = sscanf(line, "%*s %s %s", arg, extra)) > 1) return -1;
138140

139-
DIR *dir = opendir(argc == 1 ? arg : ".");
141+
const char *path = argc == 1 ? arg : ".";
142+
DIR *dir = opendir(path);
140143
if (dir == NULL) return error_handler();
141144
struct dirent *dp;
142145
struct stat info;
146+
char filename[N];
143147
while ((dp = readdir(dir)) != NULL) {
144-
printf("%-20s", dp->d_name);
145-
if (stat(dp->d_name, &info) == -1) {
148+
sprintf(filename, "%s/%s", path, dp->d_name);
149+
printf("%-20s\t%-20s", dp->d_name,
150+
get_file_type(DTTOIF(dp->d_type) & S_IFMT));
151+
if (stat(filename, &info) == -1) {
146152
printf("\n");
147153
error_handler();
148154
continue;
149155
}
150-
printf("\t%-20s\t%-5ld\n", get_file_type(info.st_mode & S_IFMT),
151-
info.st_size);
156+
printf("\t%-5ld\n", info.st_size);
152157
}
153158
closedir(dir);
154159
return 0;
@@ -243,10 +248,9 @@ int builtin_touch(char *line) {
243248
char arg[N], extra[N];
244249
if (sscanf(line, "%*s %s %s", arg, extra) != 1) return -1;
245250

246-
int fd = open(arg, O_WRONLY | O_CREAT | O_NOCTTY | O_NONBLOCK, 0666);
247-
if (fd < 0) return error_handler();
248-
int rc = utimensat(AT_FDCWD, arg, NULL, 0);
249-
if (rc) return error_handler();
251+
if (open(arg, O_WRONLY | O_CREAT | O_NOCTTY | O_NONBLOCK, 0666) == -1 ||
252+
utimensat(AT_FDCWD, arg, NULL, 0) == -1)
253+
return error_handler();
250254
return 0;
251255
}
252256

0 commit comments

Comments
 (0)