Itra
Itra

Reputation: 47

Comparing N bytes in string

I want to compare argv[1] and the string "pid", but I want to put restrict how much bytes to be compared. I used strncmp, but there are problem, if I put on third argument 3 it compares more than 3 bytes.

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]){
    if (argc < 2)
        exit(EXIT_FAILURE);
    size_t i = 3;
    if (strncmp(argv[1], "pid", i) == 0){
        printf("%ld\n", (long)getpid());
    }

}

in the terminal

   $./main pid
   343
   $ ./main pidd
   354
   $ ./main piddd
   352

Upvotes: 1

Views: 1471

Answers (3)

Abdul kareem
Abdul kareem

Reputation: 73

This might work:

int i,count=1;
char str[] = "pid";
    for (i = 0;i < 4;i++) 
   {
        if (str[i] != argv[1][i]) 
        {
            count = 0;
            break;
        }
    }
if(count==1)
  printf("%ld\n", (long)getpid());

Upvotes: 2

renga_in_stack
renga_in_stack

Reputation: 196

You can have a check like this below:

if ((strlen(argv[1]) <= i) && strncmp(argv[1], "pid", i) == 0){

But for all three possible inputs you tried, the first 3bytes are "pid". So strncmp will obviously returns 0 and is expected only.

Upvotes: 1

einpoklum
einpoklum

Reputation: 131930

strncmp() compares three bytes in all of your three calls. But because it only compares 3 bytes, you can't tell whether the argv[0] string ends after 3 characters or not.

If you want "pid" not to maych piddddd, try comparing 4 bytes, so that you hit the end-of-string marker ('\0').

Upvotes: 3

Related Questions