以windows下ini配置文件爲模板。
文件內容舉例,
[screen_attr]
real_width=1280
real_height=720
virtual_width=1280
virtual_height=720
;disp_resolution值參考
;1-720p,2-1080p,3-1440*900
disp_resolution=1
支持中文內容,註釋符號隨意,在一行的開始即可。
一、讀
待完善。
二、寫。修改某個字段值,不可用作新增。
int set_key_value(const char *title,const char *key,const char *value,const char *filename)
{
char text[100][100]={0};
FILE *fp = NULL;
fp = fopen(filename,"r");
if (NULL == fp)
{
return -1;
}
int i=0;
int get_title = 0;
int is_title = 0;
int query_success = 0;
char tmpstr[100] = {0};
while(i < 100)
{
char *ret = fgets(text[i],100,fp);
if (NULL == ret)
{
break;
}
if (query_success)
{
i++;
continue;
}
char *tmp = strchr(text[i],'=');
if (tmp)
{
is_title = 0;
}
else
{
is_title = 1;
}
if (0 == get_title)
{
if (0 == is_title)
{
i++;
continue;
}
else
{
memset(tmpstr,0,sizeof(tmpstr));
strncpy(tmpstr, "[", 2);
strcat(tmpstr,title);
strcat(tmpstr,"]");
if( 0 == strncmp(tmpstr,text[i],strlen(tmpstr)) )
{
get_title = 1;
}
i++;
continue;
}
}
else
{
if (is_title)
{
break;
}
else
{
memset(tmpstr,0,sizeof(tmpstr));
strcpy(tmpstr,key);
strcat(tmpstr,"=");
if (0 == strncmp(tmpstr,text[i],strlen(tmpstr)))
{
strcat(tmpstr,value);
memset(text[i],0,sizeof(text[i]));
sprintf(text[i],"%s\n",tmpstr);
query_success = 1;
}
i++;
continue;
}
}
}
fclose(fp);
if (0 == query_success)
{
return -1;
}
//sub
fp = fopen(filename,"w");
if (NULL == fp)
{
return -1;
}
int j=0;
while(j<i)
{
fputs(text[j],fp);
j++;
}
fclose(fp);
return 0;
}
調用方法,set_key_value(“screen_attr”,"real_width","1920","cfg.ini");將real_width由1280改爲1920。