HP C/iX Library Reference Manual (30026-90004)

Chapter 5 343
HP C/iX Library Function Descriptions
strncmp
strncmp
Compares two strings up to a maximum of
n
characters and returns an integer result of
the comparison.
Syntax
#include <string.h>
int strncmp(const char *
s1
, const char *
s2
, size_t
n
);
Parameters
s1
,
s2
Pointers to character strings.
n
Specifies the maximum number of characters to compare in both
s1
and
s2
.
Return Values
<0
s1
is less than
s2
.
=0
s1
and
s2
are equal.
>0
s1
is greater than
s2
.
Description
In the strncmp function,
s1
and
s2
are character pointers to the null-terminated character
strings to be compared. strncmp() compares at most
n
characters of both strings. Neither
string need be null-terminated if
n
is less than or equal to the length of the shorter string.
Example
The following program fragment uses strncmp() to analyze the contents of a file coded
with macros. In this example, a period (.) at the beginning of a line indicates a macro. The
program reads each line of the file and keeps a count of the number of times selected
macros are used, and prints a summary of its findings at the end.
#include <stdio.h>
main(argc, argv)
int argc;
char *argv[ ];
{
char *fgets(), line[100];
FILE *fp;
int nsh, npp, ntp, nrs, nre, npd, nip, nmisc, nlines;
nsh = npp = ntp = nrs = nre = npd = nip = nmisc = nlines = 0;
if(argc != 2) {
fprintf(stderr, "Usage: count file\n");