1

I am trying to build a directory tree.

How can you limit user input to 1-2 strings separated by spaces?

USER INPUT EXAMPLE:

mkdir directory1 (2 strings: one command one argument)

ls (1 string: one command)

Some ideas:

Tokenise user input AND

Delimiter for white-spaces to check for new string

OR Pointer to traverse the char elements of the strings?

But how do you handle for the 3rd string e.g. if (string_count > 2) {error message}

#include <stdio.h> /* For fgets(), fprintf() and printf() */
#include <stdlib.h> /* For EXIT_FAILURE */
#include <ctype.h> /* For isspace() */

// COMMANDS
char exit[4] = "exit";
char list[2] = "ls";
char commandDirectory[2] = "cd";
char makeDirectory[5] = "mkdir";
char removeDirectory[5] = "rmdir";
char directoryName[129] = "";

int userInput() {
    char string[130];

    printf("> \n");
    printf("Input a string: ");
    if (fgets(string, sizeof(string), stdin) == NULL) {
        fprintf(stderr, "Please enter at least one argument\n");
    }
    else
    {
        char *pointer;

        pointer = string;
        while (isspace((unsigned char) *pointer) != 0)
            pointer++;
        if (*pointer == '\0') {
            fprintf(stderr, "Please enter at least one argument\n");
        }
        printf("%s", string);
    }
    return 0;
}

int main(void) {
    userInput();
}
  • 2
    In `char makeDirectory[5] = "mkdir";` and others, no `'\0'` string terminator will be included, because you limited the array length. Better is `char makeDirectory[] = "mkdir";` – Weather Vane Feb 01 '16 at 23:47
  • 1
    Tokenize the input using the `strtok` function. – user3386109 Feb 01 '16 at 23:47
  • 2
    `fgets(string, sizeof(string), stdin)` is the correct first step. – chux - Reinstate Monica Feb 01 '16 at 23:51
  • Possible dup: http://stackoverflow.com/questions/33532570/c-parsing-input-text-file-into-words – Jay Elston Feb 01 '16 at 23:54
  • I like to (1) read a line, (2) break it up into an array of whitespace-separated "words" (using something like `strtok`), (3) see if the first word is one I recognize ("mkdir", "ls", etc.), then finally (4) look at the count of words I got and, if it's inappropriate for the current command, complain. – Steve Summit Feb 01 '16 at 23:59
  • just ignore when they put excess arguments – Jerfov2 Feb 02 '16 at 12:31

1 Answers1

0

the easiest way to ignore unexpected input..

after reading any expected/optional input, just loop calling getchar() until a '\n' char is read.

given your ls input. that could be:

  1. ls
  2. ls -al
  3. ls -al myfile
  4. and several other possibilities

as a second example cp

  1. cp filename1 directoryname
  2. cp filename1 filename2 directoryname
  3. cp -a --attributes-only --backup -force filename1 filename2
  4. and several other possibilites

this indicates that the premise of only 1 or 2 strings is not valid

user3629249
  • 16,402
  • 1
  • 16
  • 17