字符串数据读取测试
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct
{
int type;
char *uuid;
int mode;
int report_num;
bool led;
bool shake;
bool ring;
char *content;
} msg_t;
static void free_msgs(msg_t *msgs)
{
if (NULL == msgs)
return;
if (msgs->uuid)
{
free(msgs->uuid);
}
if (msgs->content)
free(msgs->content);
free(msgs);
}
int main()
{
char cmd[800] = "SEND_SMS,1,20210507175954-1-0-0-0-0-e682a8e69c89e4b880e4b8aae9a284e4b9a0e4bbbbe58aa1e380903035e69c883037e697a52028e5b08fe5ada6e8afade696872920e9a284e4b9a0e4bbbbe58aa1e38091efbc8ce8afb7e59ca8e5aeb6e995bfe7abafe69fa5e79c8b";
msg_t *msg = (msg_t *)malloc(sizeof(msg_t));
memset(msg, 0, sizeof(msg_t));
char *type, *uuid, *mode, *report_num, *led, *shake, *ring, *content = NULL;
strtok_r(cmd, ",", &type);
printf("cmd = %s\n", cmd);
strtok_r(type, ",", &uuid);
msg->type = atoi(type);
printf("msg->type = %d\n", msg->type);
strtok_r(uuid, "-", &mode);
msg->uuid = strdup(uuid);
printf("msg->uuid = %s \n", msg->uuid);
strtok_r(mode, "-", &report_num);
msg->mode = atoi(mode);
printf("msg->mode = %d\n", msg->mode);
strtok_r(report_num, "-", &led);
msg->report_num = atoi(report_num);
printf("msg->report_num = %d\n", msg->report_num);
strtok_r(led, "-", &shake);
msg->led = atoi(led);
printf("msg->led = %d\n", msg->led);
strtok_r(shake, "-", &ring);
msg->shake = atoi(shake);
printf("msg->shake = %d\n", msg->shake);
strtok_r(ring, "-", &content);
msg->ring = atoi(ring);
printf("msg->ring = %d\n", msg->ring);
msg->content = strdup(content);
printf("msg->content = %s \n", msg->content);
free_msgs(msg);
return 0;
}
测试
|