FENIX_coreutils/basename.c

91 lines
1.5 KiB
C
Raw Normal View History

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char ** argv) {
int suffix_present = 0, i, j;
char *basename; char c;
int basename_length = 0, last_slash = 0;
int suffix_length = 0;
if(argc > 2) {
suffix_present = 1;
}
else if(argc == 1) {
printf("\n");
return 0;
}
if(strcmp(argv[1], "//") == 0) {
printf("\n");
return 0;
}
i = 0;
for(c = argv[1][i]; c != '\0'; c = argv[1][i]) {
i++;
}
if(argv[1][i-1] == '/') {
argv[1][i-1] = '\0';
}
i = 0;
for(c = argv[1][i]; c != '\0'; c = argv[1][i]) {
if(c == '/') {
last_slash = i;
}
i++;
}
i = last_slash + 1;
for(c = argv[1][i]; c != '\0'; c = argv[1][i]) {
basename_length++; i++;
}
basename = calloc(basename_length + 1, sizeof(*basename));
if(basename == NULL) {
fprintf(stderr, "%s: Could not allocate sufficient memory\n", argv[0]);
return 1;
}
i = last_slash + 1;
for(c = argv[1][i]; c != '\0'; c = argv[1][i]) {
basename[i - (last_slash + 1)] = c;
i++;
}
basename[basename_length] = '\0';
if(suffix_present && strcmp(basename, argv[2]) != 0) {
i = 0;
for(c = argv[2][i]; c != '\0'; c = argv[2][i]) {
suffix_length++;
i++;
}
j = suffix_length - 1;
for(i = basename_length - 1; i > 0; i--) {
if(basename[i] != argv[2][j]) {
break;
}
else if(j == 0) {
basename[i] = '\0';
i = 0;
}
j--;
}
}
printf("%s\n", basename);
free(basename);
return 0;
}