c - 解析具有各种字段的消息,然后根据字段运行命令的最佳方法是什么?

标签 c parsing struct tree

所以现在我定义了一个如下所示的结构:

typedef struct rec_msg {
    uint8_t unit[4];
    uint8_t subdevice[4];
    uint8_t command[4];
    uint16_t  data[3];
    uint16_t  msg_id[1];
} rec_msg;

...我想读取结构中的字符数组,然后基于它们运行命令。现在我正在这样做,而且似乎会有一种更简洁的方法来做到这一点。

 if (strncmp((const char *)message->unit, "blah", 3) == 0)
  {
    if (strncmp((const char *)message->subdevice, "syr", 3) == 0) 
    {
      if (strncmp((const char *)message->command, "rem", 3) == 0)
      {
        // run some command
      }
      else if (strncmp((const char *)message->command, "dis", 3) == 0)
      {
        // run some command
      }
      else
      {
        DEBUG_PRINT("Message contains an improper command name");
      }
    }
    else if (strncmp((const char *)message->subdevice, "rot", 3) == 0)
    {
      if (strncmp((const char *)message->command, "rem", 3) == 0)
      {
        // run some command
      }
      else if (strncmp((const char *)message->command, "dis", 3) == 0) 
      {
        // run some command
      }
      else
      {
        DEBUG_PRINT("Message contains an improper command name");
      }
    }
    else
    {
      DEBUG_PRINT("Message contains an improper subdevice name");
    }
  }
  else
  {
    DEBUG_PRINT("Message contains the wrong unit name");
  }
}

最佳答案

不是针对一般问题的明确代码,而是将任务分解为多个步骤。伪代码如下。

对于 3 组字符串中的每一组,将匹配的文本转换为数字。建议具有相应枚举的字符串数组。 (如下图2)

enum unit_index {
  unit_blah,
  unit_N
};

const char *unit_string[unit_N] = {
  "blah"
};

enum subdevice_index {
  subdevice_syr,
  subdevice_rot,
  subdevice_N
};

const char *subdevice_string[subdevice_N] = {
  "syr"
  "rot"
};

查找匹配索引

unit_index unit = find_index(message->unit, unit_string, unit_N);
if (unit >= unit_N) {
  DEBUG_PRINT("Message contains the wrong unit name");
  return FAIL;
}

subdevice_index subdevice = find_index(message->subdevice, subdevice_string, subdevice_N);
if (subdevice >= subdevice_N) {
  DEBUG_PRINT("Message contains the wrong subdevice name");
  return FAIL;
}

// similar for command

现在代码有 3 个索引对应于 3 个文本字段。

创建索引表及相应命令

typedef struct {
  enum unit_index       unit;
  enum subdevice_index  subdevice;
  enum command_index    command;
  int (*func)();
} index2func;

index2func[] = {
  { unit_blah, subdevice_syr, command_dis, command_blah_syr_dis },
  { unit_blah, subdevice_rot, command_dis, command_blah_rot_dis },
  ...
  { unit_blah, subdevice_rpt, command_rem, command_blah_rot_rem }
};

遍历表以获得一组匹配的索引并执行命令。

关于c - 解析具有各种字段的消息,然后根据字段运行命令的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37467361/

相关文章:

c - 如何将参数从终端传递给函数

c - 如何在C中生成数组与其自身的笛卡尔积?

在 shell 中用管道连接 n 个命令?

c - for 循环用三个变量初始化

python - 将多种日期格式转换为一种格式python

Java:从 char 中解析 int 值

ruby - 在 Ruby 中使用转义换行符解析 CSV 文件?

c - 无需声明即可访问结构?

c++ - 我想解析一个 txt 文件并将其放入一个结构中

swift - 为什么选择结构而不是类?