I'm trying to emulate bash/cmd type program. I have written programs like cat, ls, grep (simple one) and kept it under \bin\ directory. This program will take user input and run programs present in \bin\ accordingly. I'm using _spawnv ()
as the argument list is going to be variable.
When I googled I found in one site its telling me last argument of _spawnv ()
is pointers to arguments value, like *argv[]
, but when I compiled its asking for const char* const*
. I know that they are not equivalent but I'm not able to figure out a way. Here is my code.
# include <stdio.h>
# include <string.h>
# include <stdlib.h>
# include <errno.h>
# include <direct.h>
# include <process.h>
# define GetCurrentDir _getcwd
# define MAX 1024
char ** tokenize (const char *) ;
int main (int argc, char *argv[])
{
char arg[MAX][MAX], input[MAX] ;
char** tokens ;
char prog[MAX], cwd[FILENAME_MAX] ;
int i, count, res = 0 ;
char** it;
while (1)
{
if (!GetCurrentDir(cwd, sizeof(cwd)))
return errno;
cwd[sizeof(cwd) - 1] = '\0';
printf ("%s\n# ", cwd) ;
fgets (input, 100, stdin) ;
tokens = tokenize(input) ;
count = 0 ;
for (it = tokens, i = 0; it && *it; ++it, i++)
{
count++ ;
strcpy (arg[i], *it) ;
free (*it) ;
}
arg[++count] = NULL ;
free(tokens) ;
prog[0] = '\0' ;
strcpy (prog,cwd) ;
strcat (prog,"\\bin\\") ;
strcat (prog, arg[0]) ;
if (strcmp(arg[0], "exit") == 0)
break ;
if ((res = _spawnv (_P_WAIT, prog, arg)) == -1 )
perror ("\nspawn error\n") ;
}
return 0 ;
}
char** tokenize(const char* input)
{
char* str = strdup(input);
int count = 0;
int capacity = 10;
char** result = malloc(capacity*sizeof(*result));
char* tok=strtok(str," ");
while(1)
{
if (count >= capacity)
result = realloc(result, (capacity*=2)*sizeof(*result));
result[count++] = tok? strdup(tok) : tok;
if (!tok) break;
tok=strtok(NULL," ");
}
free(str);
return result;
}
Also is there anyother way to do this work ? Thank you.