Home > OS >  Why does this strcmp not trigger true?
Why does this strcmp not trigger true?

Time:09-26

I am trying to make a shell program and am working on mkdir, I am reading in the user input and breaking it into segments using sscanf and then trying to use strcmp to check if the first word was "mkdir", the strcmp works if I leave the stdin as is without using sscanf. Can someone tell me why it doesn't work like this, and how to fix it? Thanks,

//#include "parser.c"
#include <stdio.h>
# include <sys/stat.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>

#ifndef MAX_BUF
#define MAX_BUF 200
#endif

int main(void)
{
    while (1) {
        printf("Enter a command: ");
        char input[20];
        char line[4][20];
        fgets(input, 20, stdin);
        sscanf(input, "%s %s", line[0], line[1]);
        if(strcmp(line[0], "mkdir")) {
            char path[MAX_BUF];
            getcwd(path, MAX_BUF);
            strcat(path, "/");
            strcat(path, line[1]);
            mkdir(path, 0700);
            printf(path);
        }
        
    
        //printf("output %s", input);
    }
}

CodePudding user response:

Change your expression:

strcmp(line[0], "mkdir")

into:

strcmp(line[0], "mkdir") == 0

A match returns zero(a) which, when treated as a boolean, is false rather than true. In other words, your if is currrenly firing for anything other than mkdir.


There are a few other problems with your code, such as its inability to create directories longer than about thirteen characters (buffer size twenty minus one for the '\0' minus six for the "mkdir "), and the fact line[1] will be some arbitrary value if you were to just type in mkdir on its own. That won't end well :-)

You could get around that last one by checking to ensure the correct number of things were scanned, with something like:

if (sscanf(input, "%s %s", line[0], line[1]) != 2) {
    output_some_error();
} else {
    your_current_processing_of_line1_and_line2();
}

The general rule is: if a failure can affect your ability to proceed safely, you should probably check for, and act on, that failure.


(a) The call strcmp(a, b) will return a value as per the following table:

Situation: a < b a == b a > b
Returns: < 0 0 > 0
Boolean equivalent: true false true
  • Related