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();
}