BTW, your bounds checking is off. You might want to double-check it. If you want to try to fix it on your own then don't look at the following code :
Code:
itsme@dreams:~/C$ cat token.c
#include <stdio.h>
#include <string.h>
int cp_delimited_token(char *string, char delimiter, int token_nr,
char *token, int max_token)
{
char *start;
char *end;
int token_len, i;
// Get token start
for(start = string, i = 0;i < token_nr;i++, start++ )
{
if((start = strchr(start, delimiter)) == NULL)
return 0;
}
// Find end of token
if((end = strchr(start, delimiter)) == NULL)
end = start + strlen(start);
token_len = end - start;
// Check bounds
if(token_len >= max_token)
token_len = max_token - 1;
// Copy token, then add '\0'
strncpy(token, start, token_len);
*(token + token_len) = '\0';
// Replace '\n' with '\0' to end of token
for(i = 0;i < strlen(token);i++)
{
if(token[i] == '\n')
token[i] = '\0';
}
return token_len;
}
int main(void)
{
char buf[10];
int i;
for(i = 0;i < 3;++i)
{
printf("%d: %s\n",
cp_delimited_token("ab,1234567890,cde", ',', i, buf, sizeof(buf)),
buf);
}
return 0;
}
itsme@dreams:~/C$ ./token
2: ab
9: 123456789
3: cde
itsme@dreams:~/C$
The fact that it cut it off at 9 is correct. 1 of the 10 bytes is reserved for the '\0'.