1 /* 2 * Copyright (c) 2007 Bret S. Lambert <blambert@gsipt.net> 3 * 4 * Public domain. 5 */ 6 7 #include <libgen.h> 8 #include <stdio.h> 9 #include <string.h> 10 #include <limits.h> 11 #include <errno.h> 12 13 int 14 main(void) 15 { 16 char path[2 * PATH_MAX]; 17 const char *dir = "junk/"; 18 const char *fname = "file.name.ext"; 19 char *str; 20 int i; 21 22 /* Test normal functioning */ 23 strlcpy(path, "/", sizeof(path)); 24 strlcat(path, dir, sizeof(path)); 25 strlcat(path, fname, sizeof(path)); 26 str = basename(path); 27 if (strcmp(str, fname) != 0) 28 goto fail; 29 30 /* 31 * There are four states that require special handling: 32 * 33 * 1) path is NULL 34 * 2) path is the empty string 35 * 3) path is composed entirely of slashes 36 * 4) the resulting name is larger than PATH_MAX 37 * 38 * The first two cases require that a pointer 39 * to the string "." be returned. 40 * 41 * The third case requires that a pointer 42 * to the string "/" be returned. 43 * 44 * The final case requires that NULL be returned 45 * and errno * be set to ENAMETOOLONG. 46 */ 47 /* Case 1 */ 48 str = basename(NULL); 49 if (strcmp(str, ".") != 0) 50 goto fail; 51 52 /* Case 2 */ 53 strlcpy(path, "", sizeof(path)); 54 str = basename(path); 55 if (strcmp(str, ".") != 0) 56 goto fail; 57 58 /* Case 3 */ 59 for (i = 0; i < PATH_MAX - 1; i++) 60 strlcat(path, "/", sizeof(path)); /* path cleared above */ 61 str = basename(path); 62 if (strcmp(str, "/") != 0) 63 goto fail; 64 65 /* Case 4 */ 66 strlcpy(path, "/", sizeof(path)); 67 strlcat(path, dir, sizeof(path)); 68 for (i = 0; i <= PATH_MAX; i += sizeof(fname)) 69 strlcat(path, fname, sizeof(path)); 70 str = basename(path); 71 if (str != NULL || errno != ENAMETOOLONG) 72 goto fail; 73 74 return (0); 75 fail: 76 return (1); 77 } 78