rendered paste body#define _GNU_SOURCE
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int buildmap_ssplit(const char *string, char ***argv, const char sep);
void buildmap_sfree(char **argv, int count);
int main(int argc, char **argv)
{
char **out;
int r,i;
#if 0
r = buildmap_ssplit("aaa x,bbb,ddd x, & asdgh x", &out, ',');
if(r>0)
for (i=0; i<r; i++) {
printf("%d: %s\n", i, out[i]);
}
buildmap_sfree(out,r);
r = buildmap_ssplit("one,two,three , ", &out, ',');
if(r>0)
for (i=0; i<r; i++) {
printf("%d: %s\n", i, out[i]);
}
buildmap_sfree(out,r);
#else
FILE *fp;
char *line = NULL;
size_t len = 0;
ssize_t read;
char *str1, *str2, *token, *subtoken;
char *saveptr1, *saveptr2;
int j;
fp = stdin;
while ((read = getline (&line, &len, fp)) != -1)
{
printf ("line %ld (%ld)=%s", (long)read,strlen(line),line);
#if 0
for (j = 1, str1 = line; ; j++, str1 = NULL)
{
token = strtok_r (str1, "=", &saveptr1);
if (token == NULL)
break;
printf ("tok%d=%s\n", j, token);
}
#else
r = buildmap_ssplit(line, &out, '=');
if(r>0)
for (i=0; i<r; i++) {
printf("%d: %s\n", i, out[i]);
}
buildmap_sfree(out,r);
#endif
}
if (line)
free (line);
#endif
return 0;
}
void buildmap_sfree(char **argv, int count) {
int i;
if (count<=0) return;
for (i=count-1; i>=0; i--) {
free(argv[i]);
}
free(argv);
}
int buildmap_ssplit(const char *string, char ***argv, const char sep)
{
int count = 0;
char *result;
char **out;
int len = strlen(string);
int whitespace = 1;
int i,j,s;
if (!string)
return -1;
result = (char*)malloc(len*sizeof(char));
if (!result) return -1;
memset(result, 0, len*sizeof(char));
/* strip off multiple white spaces */
j=0;
count=1;
for (i=0; i<len; i++) {
if (string[i] == ' ') {
if (!whitespace) {
whitespace=1;
result[j] = string[i];
j++;
}
} else {
result[j] = string[i];
j++;
whitespace = 0;
if (string[i] == sep) {
count++;
/* ignore initial white spaces */
whitespace = 1;
}
}
}
out = (char**)malloc(count*sizeof(char *));
if (!out)
{
count=-1;
goto out;
}
len = j;
count = 0;
s = 0;
for (i=0; i<len; i++) {
if (result[i] == sep) {
/* split the string */
out[count] = (char *)malloc((i-s+1)*sizeof(char));
if (!out[count])
{
for(j=0;j<=count;j++)
free(out[j]);
free(out);
count=-1;
goto out;
}
memset(out[count],0,(i-s+1)*sizeof(char));
memcpy(out[count], result+s,(i-s)*sizeof(char));
s=i+1;
count++;
}
}
if (s<len) {
out[count] = (char *)malloc((len-s+1)*sizeof(char));
if (!out[count])
{
for(k=0;k<=count;k++)
free(out[k]);
free(out);
count=-1;
goto out;
}
memset(out[count],0,(len-s+1)*sizeof(char));
memcpy(out[count], result+s,(len-s)*sizeof(char));
count++;
}
*argv=out;
out:
free(result);
return count;
}