Am working on a project where it is a communication between server client. Server opens a specific file and stores the message from the client in a buffer using while(1) for repeated communication. All am trying is manage the message like, when client sends this message : AT+REG1=5 , i want to split it ("=") in order to determine operations and values : operation = AT+REG1 And value is 5. In my code i have a struct with informations for "operation" and "value". I use strtok function to split message but it doesnt work right and i dont know why , for example i send through client AT+REG1=5 and when i split the message like :
token=strtok("AT+REG1=5","="); // points to AT+REG1
value=strtok(NULL,"="); // points to the value but returns null
It returns that value is (null) despite that it must return "5". My build for that is :
typedef enum operation{
insert,
read_reg,
info
}Operation;
typedef struct request{
Operation operation;
int ID;
int **regs;
}Request;
Function that handles the split of message:
Request *parse_request(char *buffer){
char *token=NULL,*value=NULL;
Request *rep=NULL;
rep=(Request*)malloc(sizeof(Request));
token=strtok(buffer,"=");
printf("token:%s\n",token);
value=strtok(NULL," ");
printf("value=%s\n",value);
return rep;
}
And now the main loop where i call this function after receiving the message :
char buffer[SIZE];
while(1){
//Clean buffer
memset(buffer,0,SIZE);
FD_ZERO(&readfd);
FD_SET(fd,&readfd);
timeout.tv_sec=100;
timeout.tv_usec=0;
status=select(40,&readfd,NULL,NULL,&timeout);
if(status==0){
printf("Cannot receive data from client\n");
printf("\tTime Out\n");
exit(1);
}
read_num=read(fd,buffer,sizeof(buffer));
if(read_num<0) perror("Error in reading file descriptor\n");
if(read_num>0){
request=parse_request(buffer);
break;
}
}
The main problem here is that strtok returns null in at value parameter despite that the message is AT+REG1=5 and it must show "5".