1 /* Copyright 2005 Shaun Jackman 2 * Permission to use, copy, modify, and distribute this software 3 * is freely granted, provided that this notice is preserved. 4 */ 5 6 #include <libgen.h> 7 #include <string.h> 8 9 #if defined(__GNUC__) && !defined(clang) && __OPTIMIZE_SIZE__ 10 /* 11 * GCC 12.x has a bug in -Os mode on (at least) arm v8.1-m which 12 * mis-compiles this function. Work around that by switching 13 * optimization mode 14 */ 15 #pragma GCC diagnostic ignored "-Wpragmas" 16 #pragma GCC optimize("O2") 17 #endif 18 19 char * dirname(char * path)20dirname (char *path) 21 { 22 char *p; 23 if( path == NULL || *path == '\0' ) 24 return "."; 25 p = path + strlen(path) - 1; 26 while( *p == '/' ) { 27 if( p == path ) 28 return path; 29 *p-- = '\0'; 30 } 31 while( p >= path && *p != '/' ) 32 p--; 33 while( p > path && p[-1] == '/' ) 34 p--; 35 return 36 p < path ? "." : 37 p == path ? "/" : 38 (*p = '\0', path); 39 } 40