strncmp.c 638 B

12345678910111213141516171819202122232425262728293031323334
  1. /* strncmp -- compare two strings, stop after n bytes.
  2. This function is in the public domain. */
  3. /*
  4. @deftypefn Supplemental int strncmp (const char *@var{s1}, @
  5. const char *@var{s2}, size_t @var{n})
  6. Compares the first @var{n} bytes of two strings, returning a value as
  7. @code{strcmp}.
  8. @end deftypefn
  9. */
  10. #include <ansidecl.h>
  11. #include <stddef.h>
  12. int
  13. strncmp(const char *s1, const char *s2, register size_t n)
  14. {
  15. register unsigned char u1, u2;
  16. while (n-- > 0)
  17. {
  18. u1 = (unsigned char) *s1++;
  19. u2 = (unsigned char) *s2++;
  20. if (u1 != u2)
  21. return u1 - u2;
  22. if (u1 == '\0')
  23. return 0;
  24. }
  25. return 0;
  26. }