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