/* strnlen.c - determine the length of a fixed-size string * Andrew Ho (andrew@zeuscat.com) * * Implements strnlen(), which is defined on some BSD systems and Linux * but not on Solaris. This is just like strlen(), but you provide a * maximum number of bytes to count, which saves time if you know * what the maximum allowed size of the string is. * * Compile with -DMAX=n where n is a positive integer to change the way * the demonstration driver works. * * Build: gcc -Wall -o strnlen strnlen.c * Usage: strnlen string1 [string2 [string3 ...]] */ #include #include #ifndef MAX #define MAX 5 #endif /* just like strlen(3), but cap the number of bytes we count */ static size_t strnlen(const char *s, size_t max) { register const char *p; for(p = s; *p && max--; ++p); return(p - s); } int main(int argc, char **argv) { int i; for(i = 1; i < argc; i++) printf( "strnlen(\"%s\", %d) = %d\n", argv[i], MAX, strnlen(argv[i], MAX) ); return 0; }