C strtok() and strcmp() issues

Viewed 66
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>

int main(int args, char* argv[])
{
  const int CBUFF = 1024;
  char input[CBUFF];
  char wkdir[CBUFF];
  char* command;

  printf("Welcome to MyShell...\n");

  while(1)
  {
    getcwd(wkdir, CBUFF);
    printf("%s ? ", wkdir);
    fgets(input, CBUFF, stdin);

    command = strtok(input, " ");

    if(strcmp(command, "cd") == 0)
    {
      char* path;
      path = strtok(NULL, " ");

      if(chdir(path) != 0)
      {
        printf("ERROR: COULD NOT CHANGE DIRECTORY TO SPECIFIED PATH");
      }
    }
    if(strcmp(command, "exit") == 0) break;
  }

  return 0;
}

I am running into an issue creating a very simple command shell in C. The input is only being read the way I want it too when I add a space after my directive. I know that it has something to do with my improper use of the strtok() function but am not able to figure out what I am doing wrong. I have read the documentation of <string.h> and am turning up blank.

Behavior I want: Directive "exit" to exit from program. Current behavior: Must add space after directive to get it to parse correctly ie. "exit " or "cd " is entered.

1 Answers

You left the trailing newline in the buffer. Get rid of it.

char *got = fgets(input, CBUFF, stdin);
if (!got) return ; /* EOF -- treat like exit */
size_t gotlen = strlen(got);
if (got[gotlen] == '\n') got[gotlen] = 0;
Related