我正在编写一个程序,它将读取文件并将值保存在数组中。这是我的文件:
communication1 : b8:27:eb:cf:54:2c, b8:27:eb:75:85:e4, 2000000;
communication2 : mm:27:eb:cf:54:2c, xx:27:eb:75:85:e4, 2200000;这是我的代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
struct mac{
uint8_t address_bytes [6];
};
void main(){
int count = 2, i = 0;
char *Trash[4], *Time[4];
int k=0;
int mac1[6], mac2[6];
char tempbuff[100];
char trash[20], mac_s[20], mac_d[20], time[20];
struct mac Mac1[2], Mac2[2];
int j = 0;
FILE *fptr = fopen("config", "r");
fseek(fptr, 0, SEEK_SET);
while(!feof(fptr)){
if (fgets(tempbuff,100,fptr)) {
printf("\n%s", tempbuff);
sscanf(tempbuff, "%15s : %17[^;], %17[^;], %17[^;];", trash, mac_s, mac_d, time);
Trash[i] = strdup(trash);
Time[i] = strdup(time);
sscanf(mac_s, "%x:%x:%x:%x:%x:%x", &mac1[0], &mac1[1], &mac1[2], &mac1[3], &mac1[4], &mac1[5]);
sscanf(mac_d, "%x:%x:%x:%x:%x:%x", &mac2[0], &mac2[1], &mac2[2], &mac2[3], &mac2[4], &mac2[5]);
for(j = 0; j < 6; j++){
Mac1[i].address_bytes[j] = (uint8_t) mac1[j];
Mac2[i].address_bytes[j] = (uint8_t) mac2[j];
}
printf ("Mac1[%d] is %02x:%02x:%02x:%02x:%02x:%02x and Time is %s\n", i, Mac1[i].address_bytes[0], Mac1[i].address_bytes[1], Mac1[i].address_bytes[2], Mac1[i].address_bytes[3],
Mac1[i].address_bytes[4], Mac1[i].address_bytes[5], Time[i]);
printf ("Mac2[%d] is %02x:%02x:%02x:%02x:%02x:%02x \n", i, Mac2[i].address_bytes[0], Mac2[i].address_bytes[1], Mac2[i].address_bytes[2], Mac2[i].address_bytes[3],
Mac2[i].address_bytes[4], Mac2[i].address_bytes[5]);
}
i++;
}
printf(" \n time0 is %s time1 is %s \n", Time[0], Time[1]);
fclose(fptr);
}如你所见,我是一个sscanf文件,有4个变量,然后我把mac地址分别写成sscanf类型的指针,然后尝试把它们写到一个结构数组中。我必须实现uint8_t值。
此代码的输出为:
communication1 : b8:27:eb:cf:54:2c, b8:27:eb:75:85:e4, 2000000;
Mac1[0] is b8:27:eb:cf:54:2c and Time is 2000000
Mac2[0] is b8:27:eb:75:85:e4
communication2 : mm:27:eb:cf:54:2c, xx:27:eb:75:85:e4, 2200000;
Mac1[1] is b8:27:eb:cf:54:2c and Time is 2200000
Mac2[1] is b8:27:eb:75:85:e4
time0 is 2000000 time1 is 2200000 问题是,我找不到将指针复制到结构数组的uint8_t字段中的方法。对于字符串,我已经得到了提示- strdup,那么uint8_t呢
发布于 2019-02-27 04:55:27
要像uint8_t一样复制普通字节,请使用memcpy
int main() {
uint8_t s[6] = { 0x1, 0x2, 0x3,0x4,0x5,0x6 };
uint8_t *t;
t = malloc(6*sizeof(uint8_t));
memcpy(t,s,6*sizeof(uint8_t));
printf("%x %x %x %x %x %x\n", t[0],t[1],t[2],t[3],t[4],t[5]);
}https://stackoverflow.com/questions/54893731
复制相似问题