splitting a variable number of tokens with strtok_r
I'm receiving via a named pipe commands with this format:
GETIP <machine_name> \n
<process_id>
GETNAME<ip_address> \n
<process_id>
UDATA <machine_name> <ip_address>
<process_id>
D开发者_运维知识库DATA <machine_name> \n
<process_id>
So, sample strings read from the pipe are:
GETIP lolcatzmachine
1235
UDATA cheezburger 127.0.0.1
7564
Truthfully, I don't know what the hell I'm doing here, I'm not familiar with c tokenizing. How can I alter my code to meet the requirements?
char *token;
char *commandName [10];
char machineName[200];
char ip[40];
char pid[30];
char * separator = " ";
char *brkt; // reentrant pointer, as this tokenizing will be multithreaded
for ( ; ; ) {
token=strtok_r(command_and_pid, separator, &brkt); //strtok_r is needed for multithreading
commandName = strdup(token);
//ip=strtok_r(NULL, separator, &brkt);
//pid=strtok_r(NULL, separator, &brkt);
if (token == NULL)
break;
}
Check out this. Note : didnt tested & optimized
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include "strtok.h"
//char temp[100];
char *strTok(char *string, char *delimiter)
{
static char *inputStr = NULL;
char *temp = NULL;
int i,count,j;
if (string != NULL)
{
if( inputStr != NULL)
free(inputStr);
inputStr = (char*) malloc (sizeof(char) * strlen(string));
strcpy(inputStr,string);
}
for( i = 0 ; i < strlen(inputStr) ; i++ )
{
if ( inputStr[i] == delimiter[0] )
{
count = 1;
for( j = 1 ; j < strlen(delimiter) ; j++ )
{
if ( inputStr[i+j] == delimiter[j] )
count ++;
else
break;
}
}
if ( count == strlen(delimiter) )
{
if( temp != NULL)
free(temp);
temp = (char*) malloc (sizeof(char) * i);
strncpy(temp,inputStr,i);
strcpy(inputStr,inputStr+i+strlen(delimiter));
return temp;
}
}
return inputStr;
}
/*int main()
{
char *str = strTok("title:4:int",":");
printf("%s\n",str);
str = strTok(NULL,":");
printf("%s\n",str);
str = strTok(NULL,":");
printf("%s\n",str);
str = strTok(NULL,":");
printf("%s\n",str);
str = strTok("director:int:sdjjsd",":");
printf("%s\n",str);
str = strTok(NULL,":");
printf("%s\n",str);
}*/
I ended up using a modified version of this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int
main(int argc, char *argv[])
{
char *str1, *str2, *token, *subtoken;
char *saveptr1, *saveptr2;
int j;
if (argc != 4) {
fprintf(stderr, "Usage: %s string delim subdelim\n",
argv[0]);
exit(EXIT_FAILURE);
}
for (j = 1, str1 = argv[1]; ; j++, str1 = NULL) {
token = strtok_r(str1, argv[2], &saveptr1);
if (token == NULL)
break;
printf("%d: %s\n", j, token);
for (str2 = token; ; str2 = NULL) {
subtoken = strtok_r(str2, argv[3], &saveptr2);
if (subtoken == NULL)
break;
printf(" --> %s\n", subtoken);
}
}
exit(EXIT_SUCCESS);
} /* main */
精彩评论