Separating space in text in C

I am writing a program for a school project that should emulate a Unix shell in a very simple way. It basically parses the input, and then does fork / exec. I need to be able to read the arguments in the program (and not as the arguments passed to the program from the command line) separately. For example, I will prompt:

Please enter a command:

... and I need to make out both ...

ls

OR

ls -l

but the problem is that there seems to be no easy way to do this. scanf()will pull each argument individually, but I don’t see the possibility of placing them in different slots in the char * array. For example, if I ...

char * user_input[10];
for (int i=0; i<10; i++){
    user_input[i] = (char *) malloc(100*sizeof(char));
}

for (int i=0; *(user_input[i]) != '@'; i++)
{
    scanf("%s", user_input[index]);
    index++;
}

... then it user_input[0]will receive "ls", then the cycle will begin, then it user_input[0]will receive "-l".

gets fgets . , , ... , , . ?

!

+3
4

, strtok:

char *strtok(char *str, const char *delim);
char *strtok_r(char *str, const char *delim, char **saveptr);

strtok() . strtok() , , str. , , str NULL.

strtok strtok_r .

- , () , , (, bash), , .

kilanash - GNU getopt. , .

+7

, scanf, , . , , . strtok - - .

+2

You can use strtok_r to split the string into spaces. Note that this is a destructive operation (modifies the input string).

+1
source

Try to find out if something helps you:

ANSI C Command Line Parameter Analysis Dashboard

Argtable Homepage

Regards, Tiho

+1
source

Source: https://habr.com/ru/post/1760540/


All Articles