#include
#include
#include
#include
int convert_to_argv(char *str, const char *delimiter, char *argv[], int limit)
{
int i;
int argc = 0;
char *p;
const char *ps = delimiter;
if (ps == NULL)
ps = " \t\r\n";
p = str + strspn(str, ps); /* find the real start of string */
argv[0] = strtok(p, ps);
if (argv[0] != NULL) {
for (i = 1; (p = strtok(NULL, ps)) != NULL; ++i) {
if (i >= limit) {
/*
fprintf(stderr, "to many args(argc > limit)\n");
*/
break;
}
argv[i] = p;
}
argc = i;
}
return argc;
}
/* <> 中makeargv的实现 */
int makeargv(const char *s, const char *delimiter, char ***argvp)
{
int error;
int i;
int token_num;
const char *snew;
char *t;
if ((s == NULL) || (delimiter == NULL) || (argvp == NULL)) {
errno = EINVAL;
return -1;
}
argvp = NULL;
snew = s + strspn(s, delimiter); /* snew is real start of string */
if ((t = malloc(strlen(snew) + 1)) == NULL)
return -1;
strcpy(t, snew);
token_num = 0;
if (strtok(t, delimiter) != NULL)
for (token_num = 1; strtok(NULL, delimiter) != NULL; token_num++) ;
/* create argument array for ptrs to the tokens */
if ((*argvp = malloc(token_num * sizeof(char *))) == NULL) {
error = errno;
free(t);
errno = error;
return -1;
}
/* insert ptrs to tokens into the argument array */
if (token_num == 0)
free(t);
else {
strcpy(t, snew);
**argvp = strtok(t, delimiter);
for (i = 1; i < token_num; i++)
*((*argvp+i)) = strtok(NULL, delimiter);
}
*((*argvp+token_num)) = NULL;
return token_num;
}
void free_makeargv(char **argv)
{
if (argv == NULL)
return;
if (*argv == NULL)
free(argv[0]);
free(argv);
}
阅读(1995) | 评论(0) | 转发(0) |