#define函数

一直以为#define只能宏定义简单变量和简单函数,虽然也知道宏定义编译过程中就是替换,但是今天才真正明白替换的意义:请看如下代码:
关键:define PARAM_WRITE(x,y) param_vendor_write(x,y)

#include
#define PARAM_CONFIG "/home/lkg/test/config" //配置文件路径
#define VENDOR_WRITE 0
#ifdef VENDOR_WRITE
    #define PARAM_WRITE(x,y) param_vendor_write(x,y)
#else
    #define PARAM_WRITE(x,y) param_write_cfg(x,y)
#endif
typedef struct{
    unsigned short int id;
    int offset;
}param_offset;     //根据id查找偏移进行参数设置
typedef struct {
    char c;
    int h;
    unsigned short n;
    char s[4];
}st;  //测试用例结构体
param_offset id_offset[3] =  {
    {1,0},
    {2,8},                    
    {3,108},                  
};//设置不同id写文件的偏移量用于后续查询
/*
 *根据id在文件的指定偏移处写数据
 */
int param_vendor_write(st* buffer, unsigned short int param_id){
    printf("param vendor write");
}
int param_write_cfg(st* buffer, unsigned short int param_id){
    int ret, i, offset;
    FILE *fp;
    i = 0;
    while(id_offset && id_offset[i].id){
        if(param_id == id_offset[i].id){
            offset = id_offset[i].offset;
            break;
        }
        i++;
    }//根据id查找对于偏移量
    printf("id = %d, offset = %d\n", param_id, offset);    
    if((fp = fopen(PARAM_CONFIG, "rb+")) == NULL) {
        if((fp = fopen(PARAM_CONFIG, "wb+")) == NULL) {
            printf("Can't open %s, program will to exit.\n", PARAM_CONFIG);
            return -1;
        }
    }
    fseek(fp, offset, SEEK_SET);
    fwrite(buffer, sizeof(*buffer), 1, fp);
    printf("st c = %d, h = %d n =%u s = %s \n",buffer->c, buffer->h,buffer->n,buffer->s); 
    fclose(fp);
    return 0;
}
/*
 *
 *读取文件指定id位置存储的结构体内容
 *
 */
int param_read_cfg(st* buffer, unsigned short int param_id){
    int ret, i, offset;
    FILE *fp;
    param_offset id_offset[3] =  {
        {1,0},
        {2,8},                    
        {3,108},                  
    }; 
    i = 0;
    while(id_offset && id_offset[i].id){
        if(param_id == id_offset[i].id){
            offset = id_offset[i].offset;
            break;
        }
        i++;
    }  
    printf("id = %d, offset = %d\n", param_id, offset);        
    if((fp = fopen(PARAM_CONFIG, "rb+")) == NULL) {
        printf("Can't open %s, program will to exit.", PARAM_CONFIG);
        return -1;
    }  
    fseek(fp, offset, SEEK_SET);
    fread(buffer, sizeof(*buffer), 1, fp);
    printf("st c = %d, h = %d n =%u s = %s \n",buffer->c, buffer->h,buffer->n,buffer->s);
    fclose(fp);
    return 0; 

}
int main(){
//    char version[] = "1.0.5";
    st t;
    st tt = {5,7,0,"didi"};
    st tt1 = {6,2,0,"dada"};
//    param_write_cfg(version,1);
    PARAM_WRITE(&tt,2);
    PARAM_WRITE(&tt1,3);
    param_read_cfg(&t,2);
    param_read_cfg(&t,3);
    return 0;
}    

你可能感兴趣的:(linux)