直接上代碼,代碼簡單易懂。
#include<stdio.h>
#define PARAM_CONFIG "/home/lkg/test/config"
typedef struct{
unsigned short int id;
int offset;
}param_offset;
typedef struct {
char c;
int h;
unsigned short n;
char s[4];
}st;
ram_offset id_offset[3] = {
▽ {1,0},
{2,8},
{3,108},
};
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++;
}
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;
}
int param_read_cfg(st* buffer, unsigned short int param_id){
int ret, i, offset;
FILE *fp;
~/test/param.c[+1] [c] unix utf-8 1:17/81
"param.c" 81L, 2187C written
lkg@ubuntu:~/test$ gcc param.c
lkg@ubuntu:~/test$ ./a.out
id = 2, offset = 8
st c = 5, h = 7 n =0 s = didi
id = 3, offset = 108
st c = 6, h = 2 n =0 s = dada
id = 2, offset = 8
st c = 5, h = 7 n =0 s = didi
id = 3, offset = 108
st c = 6, h = 2 n =0 s = dada
lkg@ubuntu:~/test$ vi param.c
*
*讀取文件指定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_cfg(&tt,2);
param_write_cfg(&tt1,3);
param_read_cfg(&t,2);
param_read_cfg(&t,3);
return 0;
}