|
NAME | LIBRARY | SYNOPSIS | DESCRIPTION | RETURN VALUE | ATTRIBUTES | STANDARDS | HISTORY | EXAMPLES | SEE ALSO | COLOPHON |
|
|
|
strncmp(3) Library Functions Manual strncmp(3)
strncmp - nonstrings compare
Standard C library (libc, -lc)
#include <string.h> // see memory.h(3head)
int strncmp(const char s1[], const char s2[], size_t n);
The strncmp() function is similar to strcmp(3), except it compares
only the first (at most) n bytes of s1 and s2.
It is equivalent to
memcmp(s1, s2, MIN(MIN(strnlen(s1,n),strnlen(s2,n))+1, n))
See memcmp(3).
For an explanation of the terms used in this section, see
attributes(7).
┌──────────────────────────────────────┬───────────────┬─────────┐
│ Interface │ Attribute │ Value │
├──────────────────────────────────────┼───────────────┼─────────┤
│ strncmp() │ Thread safety │ MT-Safe │
└──────────────────────────────────────┴───────────────┴─────────┘
C11, POSIX.1-2008.
POSIX.1-2001, C89, SVr4, 4.3BSD.
The program below can be used to demonstrate the operation of
strncmp().
$ ./strncmp ABC AB 3;
<strn1> is greater than <strn2> (67)
$ ./strncmp ABC AB 2;
<strn1> and <str2> are equal in the first 2 bytes
Program source
// strncmp.c
// Licensed under GNU General Public License v2 or later.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int
main(int argc, char *argv[])
{
int res;
if (argc != 4) {
fprintf(stderr, "Usage: %s <strn1> <strn2> <n>\n", argv[0]);
exit(EXIT_FAILURE);
}
res = strncmp(argv[1], argv[2], atoi(argv[3]));
if (res == 0) {
printf("<strn1> and <strn2> are equal");
printf(" in the first %d bytes\n", atoi(argv[3]));
printf("\n");
} else if (res < 0) {
printf("<strn1> is less than <strn2> (%d)\n", res);
} else {
printf("<strn1> is greater than <strn2> (%d)\n", res);
}
exit(EXIT_SUCCESS);
}
memory.h(3head), memcmp(3), strncasecmp(3), wcsncmp(3)
This page is part of the man-pages (Linux kernel and C library
user-space interface documentation) project. Information about
the project can be found at
⟨https://www.kernel.org/doc/man-pages/⟩. If you have a bug report
for this manual page, see
⟨https://git.kernel.org/pub/scm/docs/man-pages/man-pages.git/tree/CONTRIBUTING⟩.
This page was obtained from the tarball man-pages-6.19.tar.gz
fetched from
⟨https://mirrors.edge.kernel.org/pub/linux/docs/man-pages/⟩ on
2026-09-09. If you discover any rendering problems in this HTML
version of the page, or you believe there is a better or more up-
to-date source for the page, or you have corrections or
improvements to the information in this COLOPHON (which is not
part of the original manual page), send a mail to
man-pages@man7.org
Linux man-pages 6.19 2026-08-10 strncmp(3)
Pages that refer to this page: memory.h(3head), strncasecmp(3), wcsncmp(3), signal-safety(7)