我正在将 conf 数据从 struct 处理到 char 数组缓冲区。数据已成功复制,但问题是 null 也因大小而从结构中复制。我怎样才能得到没有 null 的数据。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_DEVICE 5
#define MAX_CONF_PORT 3
typedef struct
{
unsigned char id[6];
unsigned char domain[32];
unsigned char ports[MAX_CONF_PORT][5];
}DEV_CONF_DATA;
#define SIZE_OF_DEV_CONF_DATA sizeof(DEV_CONF_DATA)
typedef union {
DEV_CONF_DATA data;
unsigned char bytes[SIZE_OF_DEV_CONF_DATA];
}DEV_CONF_BUFF;
typedef struct {
DEV_CONF_BUFF conf[MAX_DEVICE];
}DEVICE;
int main()
{
int i = 0;
DEVICE device;
unsigned char tx_buff[1024];
unsigned char *dest_ptr = tx_buff;
device.conf[0].data= (DEV_CONF_DATA) {"ABC,","embed-service.net,","8111,","8112,",","};
device.conf[1].data= (DEV_CONF_DATA) {"XYZ,","embed-service.net,","7111,","7112,",","};
memcpy(dest_ptr,device.conf[0].bytes,SIZE_OF_DEV_CONF_DATA);
dest_ptr += SIZE_OF_DEV_CONF_DATA;
memcpy(dest_ptr,device.conf[1].bytes,SIZE_OF_DEV_CONF_DATA);
dest_ptr += SIZE_OF_DEV_CONF_DATA;
for(i=0;i<SIZE_OF_DEV_CONF_DATA;i++)
if( tx_buff[i] == 0)
printf("%s", " null ");
else
printf("%c", tx_buff[i]);
printf("\n\n\n");
for(i=SIZE_OF_DEV_CONF_DATA;i<SIZE_OF_DEV_CONF_DATA*2;i++)
if( tx_buff[i] == 0)
printf("%s", " null ");
else
printf("%c", tx_buff[i]);
}
这是我的输出:
ABC, null null embed-service.net, null null null null null null null null null null null null null 8111,8112, null null null null
XYZ, null null embed-service.net, null null null null null null null null null null null null null 7111,7112, null null null null
我想要像这样在缓冲区中整洁干净的数据,
ABC,embed-service.net,8111,8112,,XYZ,embed-service.net,7111,7112,,
