Use an int to hold the result of fgetc (bug noted by David Kimdon).
[oweals/busybox.git] / coreutils / basename.c
index 5fe5e0f0391da740cba9c6a0dd0ce8c978944819..bdbcec17abd0e09a0f5dbee09a3aad812d9d35df 100644 (file)
@@ -2,8 +2,8 @@
 /*
  * Mini basename implementation for busybox
  *
- * Copyright (C) 1999,2000 by Lineo, inc.
- * Written by Erik Andersen <andersen@lineo.com>, <andersee@debian.org>
+ * Copyright (C) 1999,2000 by Lineo, inc. and Erik Andersen
+ * Copyright (C) 1999,2000,2001 by Erik Andersen <andersee@debian.org>
  *
  * This program is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
  *
  */
 
-#include "internal.h"
-#include <stdio.h>
+/* getopt not needed */
+
+#include <stdlib.h>
+#include "busybox.h"
+#include <string.h>
 
 extern int basename_main(int argc, char **argv)
 {
-       char* s, *s1;
+       int m, n;
+       char *s;
 
        if ((argc < 2) || (**(argv + 1) == '-')) {
-               usage("basename [file ...]\n");
+               show_usage();
        }
+
        argv++;
 
-       s1=*argv+strlen(*argv)-1;
-       while (s1 && *s1 == '/') {
-               *s1 = '\0';
-               s1=*argv+strlen(*argv)-1;
+       s = get_last_path_component(*argv);
+
+       if (argc>2) {
+               argv++;
+               n = strlen(*argv);
+               m = strlen(s);
+               if (m>n && strncmp(s+m-n, *argv, n)==0)
+                       s[m-n] = '\0';
        }
-       s = strrchr(*argv, '/');
-       printf("%s\n", (s)? s + 1 : *argv);
-       exit(TRUE);
+       puts(s);
+       return EXIT_SUCCESS;
 }
-