2020-12-12 06:33:20 +00:00
|
|
|
#define _POSIX_C_SOURCE 200809L
|
|
|
|
|
2020-12-02 02:31:58 +00:00
|
|
|
#include <stdio.h>
|
|
|
|
#include <string.h>
|
|
|
|
|
|
|
|
int main(int argc, char ** argv) {
|
|
|
|
int i, last_slash = -1, length;
|
|
|
|
|
2022-10-06 07:12:56 +00:00
|
|
|
/* If no path given, print / per the POSIX spec */
|
2020-12-02 02:31:58 +00:00
|
|
|
if(argc == 1) {
|
|
|
|
printf("/\n");
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
2022-10-06 07:12:56 +00:00
|
|
|
/* Same if // is given */
|
2020-12-02 02:31:58 +00:00
|
|
|
if(strcmp(argv[1], "//") == 0) {
|
|
|
|
printf("/\n");
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
2022-10-06 07:12:56 +00:00
|
|
|
/* Oh, look, we use strlen here. */
|
2020-12-02 02:31:58 +00:00
|
|
|
length = strlen(argv[1]);
|
|
|
|
|
2022-10-06 07:12:56 +00:00
|
|
|
/* Replace terminal slash (if present) with null */
|
2020-12-02 02:31:58 +00:00
|
|
|
if(argv[1][length - 1] == '/') {
|
|
|
|
argv[1][length - 1] = '\0';
|
|
|
|
}
|
|
|
|
|
2022-10-06 07:12:56 +00:00
|
|
|
/* Find last slash */
|
2020-12-02 02:31:58 +00:00
|
|
|
for(i = 0; i < length; i++) {
|
|
|
|
if(argv[1][i] == '/') {
|
|
|
|
last_slash = i;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-10-06 07:12:56 +00:00
|
|
|
/* If we didn't find a slash, assume PWD per POSIX spec */
|
2020-12-02 02:31:58 +00:00
|
|
|
if(last_slash == -1) {
|
|
|
|
printf(".\n");
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
2022-10-06 07:12:56 +00:00
|
|
|
/* Replace last slash with null to truncate basename */
|
2020-12-02 02:31:58 +00:00
|
|
|
argv[1][last_slash] = '\0';
|
|
|
|
|
2022-10-06 07:12:56 +00:00
|
|
|
/* If the dirname is //, /, or blank, print a single slash. */
|
2020-12-02 02:31:58 +00:00
|
|
|
if(strcmp(argv[1], "//") == 0 || strcmp(argv[1], "") == 0 ||
|
|
|
|
strcmp(argv[1], "/") == 0) {
|
|
|
|
printf("/\n");
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
2022-10-06 07:12:56 +00:00
|
|
|
/* Remove any trailing slashes from the dirname */
|
2020-12-02 02:31:58 +00:00
|
|
|
for(i = last_slash - 1; argv[1][i] == '/'; i--) {
|
|
|
|
argv[1][i] = '\0';
|
|
|
|
}
|
|
|
|
|
|
|
|
printf("%s\n", argv[1]);
|
|
|
|
|
|
|
|
return 0;
|
|
|
|
}
|