Long time C programmer, first time poster.
Why not look at it as a parsing problem.
The packet is one or more digits, and then a string operation.
So something like "int parse_packet(char *data, int len, int *table_id, int *operation)"
As I said, I'm new here, so if this oversteps the line then let me know...
Code:
#include <string.h>
#include <stdio.h>
/*********************************************************************************/
/* Definitions for the packet operations */
/*********************************************************************************/
char *operations[] = {
"add",
"start",
"stop",
"delete"
};
enum op_code { // Must match order in operations[]
op_add = 0,
op_start = 1,
op_stop = 2,
op_delete = 3
};
/*********************************************************************************/
/* Validate and parse the packet */
/*********************************************************************************/
int parse_packet(const char *data, int len, int *table_id, enum op_code *operation) {
int id_temp = 0, op_temp;
if(len == 0) {
return 0; // Failed
}
if(data[0] < '0' || data[0] > '9') {
return 0; // Must begin with a digit
}
// convert id to a number
while((data[0] >= '0' && data[0] <= '9') && len > 0) {
id_temp = id_temp * 10 + data[0] - '0';
data++;
len--;
}
if(len == 0 || data[0] != '_') {
return 0; // Missing underscore
}
data++;
len--;
// Look for the operation
for(op_temp = 0; op_temp < sizeof(operations)/sizeof(char *); op_temp++) {
int this_op_len = strlen(operations[op_temp]);
if(len >= this_op_len) {
if(memcmp(data,operations[op_temp],this_op_len) == 0) {
break; // Found a match
}
}
}
// Was a matching operation not found?
if(op_temp == sizeof(operations)/sizeof(char *)) {
printf("operation not found\n");
return 0; // Operation not found
}
// Success - copy across results
*table_id = id_temp;
*operation = op_temp;
return 1; // Success
}
/*********************************************************************************/
/* Allow testing from the command line */
/*********************************************************************************/
int main(int argc, char *argv[]) {
int table_id;
enum op_code op_id;
if(argc != 2) {
fprintf(stderr,"No test data supplied\n");
return 1;
}
if(parse_packet(argv[1],strlen(argv[1]), &table_id, &op_id)) {
printf("'%s' has table id %i and op_id of %i ('%s')\n",
argv[1], table_id, op_id, operations[op_id]);
} else {
printf("Data not valid\n");
}
return 0;
}