大家好,我是杂烩君。
本次我们再来分享几个实用的代码小片段。
快速获取结构体成员大小
获取结构体成员大小及偏移量的方式有多种。最简便的方式:
代码:
左右滑动查看全部代码>>>
// 微信公众号:嵌入式大杂烩
#include
// 获取结构体成员大小
#define GET_MEMBER_SIZE(type, member) sizeof(((type*)0)->member)
// 获取结构体成员偏移量
#define GET_MEMBER_OFFSET(type, member) ((size_t)(&(((type*)0)->member)))
typedef struct _test_struct0
{
char x;
char y;
char z;
}test_struct0;
typedef struct _test_struct1
{
char a;
char c;
short b;
int d;
test_struct0 e;
}test_struct1;
int main(int arc, char *argv[])
{
printf("GET_MEMBER_SIZE(test_struct1, a) = %ld
", GET_MEMBER_SIZE(test_struct1, a));
printf("GET_MEMBER_SIZE(test_struct1, c) = %ld
", GET_MEMBER_SIZE(test_struct1, c));
printf("GET_MEMBER_SIZE(test_struct1, b) = %ld
", GET_MEMBER_SIZE(test_struct1, b));
printf("GET_MEMBER_SIZE(test_struct1, d) = %ld
", GET_MEMBER_SIZE(test_struct1, d));
printf("GET_MEMBER_SIZE(test_struct1, e) = %ld
", GET_MEMBER_SIZE(test_struct1, e));
printf("test_struct1 size = %ld
", sizeof(test_struct1));
printf("GET_MEMBER_OFFSET(a): %ld
", GET_MEMBER_OFFSET(test_struct1, a));
printf("GET_MEMBER_OFFSET(c): %ld
", GET_MEMBER_OFFSET(test_struct1, c));
printf("GET_MEMBER_OFFSET(b): %ld
", GET_MEMBER_OFFSET(test_struct1, b));
printf("GET_MEMBER_OFFSET(d): %ld
", GET_MEMBER_OFFSET(test_struct1, d));
printf("GET_MEMBER_OFFSET(e): %ld
", GET_MEMBER_OFFSET(test_struct1, e));
return 0;
}
运行结果:
文件操作
文件操作平时用得很多,为了方便使用,可以自己根据实际需要再封装一层:
代码:
左右滑动查看全部代码>>>
// 微信公众号:嵌入式大杂烩
#include
static int file_opt_write(const char *filename, void *ptr, int size)
{
FILE *fp;
size_t num;
fp = fopen(filename, "wb");
if(NULL == fp)
{
printf("open %s file error!
", filename);
return -1;
}
num = fwrite(ptr, 1, size, fp);
if(num != size)
{
fclose(fp);
printf("write %s file error!
", filename);
return -1;
}
fclose(fp);
return num;
}
static int file_opt_read(const char *filename, void *ptr, int size)
{
FILE *fp;
size_t num;
fp = fopen(filename, "rb");
if(NULL == fp)
{
printf("open %s file error!
", filename);
return -1;
}
num = fread(ptr, 1, size, fp);
if(num != size)
{
fclose(fp);
printf("write %s file error!
", filename);
return -1;
}
fclose(fp);
return num;
}
typedef struct _test_struct
{
char a;
char c;
short b;
int d;
}test_struct;
int main(int arc, char *argv[])
{
#define FILE_NAME "./test_file"
test_struct write_data = {0};
write_data.a = 1;
write_data.b = 2;
write_data.c = 3;
write_data.d = 4;
printf("write_data.a = %d
", write_data.a);
printf("write_data.b = %d
", write_data.b);
printf("write_data.c = %d
", write_data.c);
printf("write_data.d = %d
", write_data.d);
file_opt_write(FILE_NAME, (test_struct*)&write_data, sizeof(test_struct));
test_struct read_data = {0};
file_opt_read(FILE_NAME, (test_struct*)&read_data, sizeof(test_struct));
printf("read_data.a = %d
", read_data.a);
printf("read_data.b = %d
", read_data.b);
printf("read_data.c = %d
", read_data.c);
printf("read_data.d = %d
", read_data.d);
return 0;
}