I am trying to parse a char * array into tokens and I am researching strtok. However whenever I run my code, it doesn't return anything into my temporary value and I was wondering what I was doing wrong
int length;
int i = 0;
int tokenCounter = 0;
int commandCounter = -1;
char *tempToken;
char tempInput[MAX_LINE];
length = read(STDIN_FILENO, tempInput, MAX_LINE);
commandCounter = -1;
if (length < 0)
{
perror ("There was an error reading the command");
}
else if (length == 0)
{
exit (0);
}
else
{
for (i = 0; i < length; ++i)
{
if (tempInput[i] == "\n" || tempInput[i] == ' ' || tempInput == "\t")
{
/*
if (commandCounter != -1)
{
pTokens[tokenCounter] = &tempInput[commandCounter];
++tokenCounter;
}
tempInput [i] = '\0';
commandCounter = -1;
*/
}
else
{
tempToken = strtok (tempInput, " \n");
while (tempToken != NULL)
{
strcpy(pTokens[tokenCounter], tempToken);
tempToken = strtok (tempInput, " \n");
}
++tokenCounter;
}
}
}
pTokens[tokenCounter] = NULL;
tempToken = strtok (tempInput, " \n");
Other than the first time NULL
pointer has to be passed to strtok
, I mean inside the while
loop, only NULL
has to be passed instead of the string.
tempToken = strtok (NULL, " \n");