概述
目录
文章目录
前言
一、ini库头文件定义
二、配置文件写接口
2.配置文件读接口
总结
前言
本文主要介绍linux下ini配置文件的读取与写入操作,提供linux c API接口供使用开发。
一、ini库头文件定义
头文件定义如下所示:
#ifndef _FILECONF_H_
#define _FILECONF_H_
/*
* pcFileName:配置文件全路径名称
* pcKey:配置文件key索引
* pcValue:配置文件key值
*
*/
int ModifyParam(char *pcFileName, char *pcKey, char *pcValue);
int ReadParam(char *pcFileName, char *pcKey, char *pcValue);
#endif
二、配置文件写接口
int CopyFile(char *pcDstFile, char *pcSrcFile)
{
FILE *fpr = NULL;
FILE *fpw = NULL;
int iLen = 0;
int iFileLen = 0;
int iSize = 0;
char acBuf[4096];
if (NULL == pcDstFile || NULL == pcSrcFile)
{
return -1;
}
fpr = fopen(pcSrcFile, "rb");
if (fpr == NULL)
{
perror("open read file:");
return -1;
}
fpw = fopen(pcDstFile, "wb");
if (fpw == NULL)
{
printf("[%s]open write file %sn", __FUNCTION__, pcDstFile);
perror("open write file error:");
return -1;
}
while (1)
{
iLen = fread(acBuf, 1, sizeof(acBuf), fpr);
if (iLen <= 0)
{
printf("read file overn");
break;
}
iSize = fwrite(acBuf, 1, iLen, fpw);
if (iSize != iLen)
{
perror("wirte file error:");
fclose(fpr);
fclose(fpw);
return -1;
}
iFileLen += iLen;
}
fflush(fpw);
fsync(fileno(fpw));
fclose(fpr);
fclose(fpw);
return iFileLen;
}
int ModifyParam(char *pcFileName, char *pcKey, char *pcValue)
{
FILE *pOldFile = NULL;
FILE *pNewFile = NULL;
char acTmpName[128];
char acBuf[256];
int iFlag = 0;
pOldFile = fopen(pcFileName, "rb");
if (NULL == pOldFile)
{
printf("[%s] open file %s errorn", __FUNCTION__, pcFileName);
perror(":");
return -1;
}
snprintf(acTmpName, sizeof(acTmpName), "%s~", pcFileName);
pNewFile = fopen(acTmpName, "wb");
if (NULL == pNewFile)
{
printf("[%s] open file %s errorn", __FUNCTION__, acTmpName);
perror(":");
fclose(pOldFile);
return -1;
}
while (fgets(acBuf, sizeof(acBuf), pOldFile))
{
if (memcmp(acBuf, pcKey, strlen(pcKey)) == 0)
{
snprintf(acBuf, sizeof(acBuf), "%s=%sn", pcKey, pcValue);
fputs(acBuf, pNewFile);
iFlag++;
}
else
{
fputs(acBuf, pNewFile);
}
}
// 如果没有此项,则添加一项
if (0 == iFlag)
{
snprintf(acBuf, sizeof(acBuf), "%s=%sn", pcKey, pcValue);
fputs(acBuf, pNewFile);
}
fflush(pNewFile);
fsync(fileno(pNewFile));
fclose(pOldFile);
fclose(pNewFile);
//rename(acTmpName, pcFileName);
CopyFile(pcFileName, acTmpName);
return 0;
}
2.配置文件读接口
int ReadParam(char *pcFileName, char *pcKey, char *pcValue)
{
FILE *pFile = NULL;
char acBuf[128];
char *pcPos = NULL;
int iLen = 0;
int iRet = -1;
pFile = fopen(pcFileName, "rb");
if (NULL == pFile)
{
printf("[%s] open file %s errorn", __FUNCTION__, pcFileName);
perror(":");
return -1;
}
while (fgets(acBuf, sizeof(acBuf), pFile))
{
if (memcmp(acBuf, pcKey, strlen(pcKey)) == 0)
{
pcPos = acBuf;
strsep(&pcPos, "=");
if (NULL == pcPos)
{
printf("line:%s, param error!!!n", acBuf);
break;
}
iLen = strlen(pcPos);
if (iLen > 0)
pcPos[iLen-1] = '