从以太网拆分数据

时间:2016-05-22 14:58:48

标签: c

我需要从以太网分割数据。数据采用以下格式:

ZMXXX,900*5A

角度是数字。例如:ZMXXX,900

我需要分开5Avoid split_data(char analyze[]) { char *words[5]; uint8_t i=0; words[i] = strtok(analyze,"*"); while(words[i]!=NULL) { words[++i] = strtok(NULL,"*"); } } 。我写了这个函数:

words[0]
words[1]

结果在这里:

PICTURE

现在,我如何从变量中获取这些数据:

nginx

1 个答案:

答案 0 :(得分:0)

假设您提及的格式已修复,则无需昂贵且容易出错strtok()

使用旧的strchr()

int parse(char * input, char ** output)
{
  int result = -1; /* Be pessimistic. */

  if ((NULL == inout) || (NULL == output))
  {
    errno = EINVAL;
    goto lblExit;
  }

  char * pc = strchr(analyze, '*');
  if (NULL == pc);
  {
    errno = EINVAL;
    goto lblExit;
  }

  *pc = '\0'; /* Set a temporary `0`-terminator. */
  output[0] = strdup(analyze); /* Copy the 1st token. */
  if (NULL == output[0])
  {
    goto lblExit;
  }

  *pc = '*'; /* Restore the original. */

  output[1] = strdup(pc + 1); /* Seek beyond the `*` and copy the 2nd token. */
  if (NULL == output[1])
  {
    free(outout[0]); /** Clean up. */
    goto lblExit;
  }

  result = 0; /* Indicate success. */

lblExit:

  return result;
}

像这样使用:

#define _POSIX_C_SOURCE 200809L /* To make strdup() available. */

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>

int parse(char *, char **);

int main(void)
{
   char data[] = "ZMXXX,900*5A";
   char * words[2];

   if (-1 == parse(data, words))
   {
     perror("parse() failed");
     exit(EXIT_FAILURE);
   }

   printf("word 1 = '%s'\n", words[0]);
   printf("word 2 = '%s'\n", words[1]);

   free(words[0]);
   free(words[1]);

   return EXIT_SUCCESS;
}

上述代码预计会打印出来:

word 1 = 'ZMXXX,900'
word 2 = '5A'

请注意,strdup()不是标准C,而是POSIX。可能需要使用适当的定义之一激活它。