c - 从以太网分割数据

标签 c

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

ZMXXX,angle*CHCK

其中角度是数字。例如:ZMXXX,900*5A

我需要分开的ZMXXX,9005A。我写了这个函数:

void split_data(char analyze[])
{    
    char *words[5]; uint8_t i=0;
    words[i] = strtok(analyze,"*");

    while(words[i]!=NULL)
    {
        words[++i] = strtok(NULL,"*");
    }
}

结果在这里:

PICTURE

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

words[0]
words[1]

最佳答案

假设您提到的格式是固定的,则不需要昂贵且容易出错的 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。它可能需要使用适当的定义之一来激活。

关于c - 从以太网分割数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37375895/

相关文章:

c - 连续迭代 RGB?

c - 总结c中的行,显示列中的垃圾数字

c - 在 while 循环中平均整数。 C语言

c - 为什么某些 C 编译器会在奇怪的地方设置函数的返回值?

ios - 如何剥离 Cocoa Touch Frameworks

c - 目标文件重定位表中条目的含义

c - 我不明白这个 #define 语句是干什么用的

c - C 语言的字典顺序

c - 您将如何按行打印二叉树?

c - 为什么同一结构变量的多个声明没有错误