配置文件读写案例

一. 配置文件读写案例实现分析

1、 功能划分

a) 界面测试(功能集成)

自己动手规划接口模型。

b) 配置文件读写

1)配置文件读(根据key,读取valude

2)配置文件写(输入keyvalude

3)配置文件修改(输入keyvalude

4)优化 ===》接口要求紧 模块要求松

二.代码实现

cfg_op.h

#ifndef __CFG_OP_H

#define __CFG_OP_H

#ifdef  __cplusplus
extern "C" {
#endif
//写配置项
int writeCfg(const char *filename,const char*key,const char*value);
//读配置项
int readCfg(const char *filename,const char*key, char*value);

//去除字符串中前后的空格
int trimSpace(char*inStr,char*out);  

#ifdef  __cplusplus
}

#endif
#endif
cfg_op.c

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MaxLine 2048
//读配置项
int readCfg(const char *filename,const char*key, char*valuebuf)
{
    int ret = 0;
    FILE *fp = NULL;
    char buf[MaxLine];
    char* tmp =NULL;
    fp = fopen(filename,"r");
    if (fp == NULL)
    {
        ret = -1;
        return ret;
    }
    //key1  =    abcdefg
    while (!feof(fp))
    {
        memset(buf,0,sizeof(buf));

        fgets(buf,MaxLine,fp);
    //    printf("buf:%s",buf);
        tmp = strchr(buf,'=');
        if (tmp==NULL)//没有等号
        {
            continue;
        }
        tmp = strstr(buf,key);//判断所在行是否有key
        if (tmp == NULL)
        {
            continue;
        }
        tmp = tmp + strlen(key);
        tmp = strchr(tmp,'=');
        if (tmp == NULL)
        {
            continue;
        }
        tmp = tmp+1;
        //去除tmp前后空格
        ret = trimSpace(tmp,valuebuf);
        if (ret!=0)
        {
            printf("func trimSpace() err :%d\n",ret);
            return ret ;
        }
    } 
    return ret;
}

//写配置项
//实现流程
//循环读取每一行,检查key配置项是否存在,若存在则修改对应的value
//若不存在,在文件末尾添加  key=value

int writeCfg(const char *filename,const char*key,const char*valuebuf)
{
    int ret = 0,iTag = 0,length=0;
    FILE *fp = NULL;
    char linebuf[MaxLine];
    char* tmp =NULL;
    char filebuf[1024*8]={0};

    if (filename==NULL||key==NULL||valuebuf==NULL)
    {
        printf("func writeCfg() param err\n");
        ret = -1;
        return ret;
    }
    fp = fopen(filename,"a+");//读写的方式打开文件
    if (fp == NULL)
    {
        ret = -1;
        printf("func fopen err:%d\n",ret);
        return ret;
    }
    fseek(fp,0L,SEEK_END);//文件指针定位到文件末尾
    length = ftell(fp);
    fseek(fp,0L,SEEK_SET);//文件指针定位到文件开头

    if (length > 1024*8)
    {
        ret = -1;
        printf("file > 8K not support\n");
        return ret;
    }
    while (!feof(fp))
    {
        //循环读取一行
        memset(linebuf,0,sizeof(linebuf));
        tmp = fgets(linebuf,MaxLine,fp);
        if (tmp ==NULL)
        {
            break;
        }
        //key关键字是否在本行
        tmp = strstr(linebuf,key);
        if (tmp == NULL)//不在本行
        {
            strcat(filebuf,linebuf);//追加本行到filebuf中
            continue;//继续下轮循环
        }
        else//在本行 将新的key = value copy到filebuf中
        {
            sprintf(linebuf,"%s = %s\n",key,valuebuf);//将新的key = value 覆盖掉旧的
            strcat(filebuf,linebuf);
            iTag = 1;//标志位 key在本行
        }
    }
    //key不在文件中,在文件末尾追加
    if (iTag == 0)
    {
        ret = fprintf(fp,"%s = %s\n",key,valuebuf);
        if (ret == -1)
        {
            printf("func sprintf() error\n");
            return ret;
        }    
        if (fp != NULL)
        {
            fclose(fp);
        }    
    }
    else//key存在文件中  创建新文件覆盖旧文件
    {
        if (fp!=NULL)
        {
            //关闭原来的文件
            fclose(fp);
        }
        fp = fopen(filename,"w+t");
        if (fp == NULL)
        {
            ret = -1;
            printf("func fopen() err \n");
            return ret;
        }
        ret = fputs(filebuf,fp);
        if ( ret < 0 )
        {
            printf("func fputs err \n");
            return ret;
        }
        if (fp!=NULL)
        {
            fclose(fp);
        }
    }
    return 0;
}
//去除字符串前后的空格
int trimSpace(char*inStr,char*out)  
{  
    char *p = inStr;  
    int ret = 0;  
    int i;  
    if (p==NULL)  
    {  
        ret = -1;  
        return;  
    }  
    for (i=0;p[i]!='\0';i++)  
    {  
        if (p[i]!=' ')  
        {  
            *out++ = p[i];  
        }  
    }  
    *out='\0';  

    return ret;  
}  
test.c

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "cfg_op.h"

#define CFGNAME "e:/mycfg.ini"

void memu()
{
    printf("======================\n");
    printf("1.测试写配置文件\n");
    printf("2.测试读配置文件\n");
    printf("0.退出配置文件\n");
    printf("======================\n");
}
int TwriteCfg()
{
    char key[1024] = {0};
    char valuebuf[1024] = {0};
    int ret = 0;
    //从键盘获取输入
    printf("\n请键入key:");
    scanf("%s",key);
    printf("\n请键入value:");
    scanf("%s",valuebuf);
    printf("您的输入是:%s = %s\n",key,valuebuf);

    ret = writeCfg(CFGNAME,key,valuebuf);
    if (ret!=0)
    {
        printf("func writeCfg err:%d\n",ret);
        return ret;
    }
    return ret;
}
int TreadCfg()
{
    char key[1024] = {0};
    char valuebuf[1024] = {0};
    int ret = 0;
    //从键盘获取输入
    printf("\n请键入key:");
    scanf("%s",key);
    
    ret = readCfg(CFGNAME,key,valuebuf);

    if (ret!=0)
    {
        printf("func readCfg err:%d\n",ret);
        return ret;
    }
    printf("value:%s\n",valuebuf);
    return ret;
}
int main()
{
    int choice;

    for (;;)
    {
        memu();
        scanf("%d",&choice);
        switch(choice)
        {
        case 1://写配置项
            TwriteCfg();
            break;
        case 2://读配置项
            TreadCfg();
            break;
        case 0:
            exit(0);
            break;
        default:
            exit(0);
        }
    }
    system("pause");
    return 0;
}
图形界面




  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
纯c读写ini配置文件 用c/c++读写ini配置文件有不少第三方的开源库,如iniparser、libini、rwini、UltraLightINIParser等,但都不理想,往往代码较大、功能较弱、 接口使用不方便。尤其在大小写处理、前后空格、各种注释、跨平台换行符支持、带引号字符串处理、无section操作、原格式保持等方面存在问题。 现将本人精心制作的ini读写程序源码奉献给大家,纯c编写,简洁好用。支持windows和linux。 主要特点: 1、支持;和#注释符号,支持行尾注释。 2、支持带引号'或"成对匹配的字符串,提取时自动去引号。引号中可带其它引号或;#注释符。 3、支持无section或空section(名称为空)。 4、支持10、16、8进制数,0x开头为16进制数,0开头为8进制。 5、支持section、key或=号前后带空格。 6、支持\n、\r、\r\n或\n\r换行格式。 7、不区分section、key大小写,但写入时以新串为准,并保持其大小写。 8、新增数据时,若section存在则在该节最后一个有效数据后添加,否则在文件尾部添加。 9、支持指定key所在整行删除,即删除该键值,包括注释。 10、可自动跳过格式错误行,修改时仍然保留。 11、修改时保留原注释:包括整行注释、行尾注释(包括前面空格)。 12、修改时保留原空行。以上三点主要是尽量保留原格式。 不足之处: 1、不支持单key多value(逗号分割),只能一次性提取后自行处理。 2、不支持同名重复section和key。(重复section可视为错误,重复key则可能造成分歧) 3、不能提取所有section或key名称。 使用只需两个文件inirw.h、inirw.c,另有测试程序和工程文件,支持windows和linux。
以下是一个简单的实例,演示如何使用 C 语言读写 Linux 下的配置文件。 假设我们有一个名为 "config.ini" 的配置文件,内容如下: ``` [database] host = localhost username = root password = password123 port = 3306 [server] ip = 127.0.0.1 port = 8080 ``` 我们要使用 C 语言读取这个配置文件,并将其中的值存储在内存中,以便我们在程序中使用。 首先,我们需要定义一个结构体来存储配置文件中的值: ```c typedef struct { char database_host[100]; char database_username[100]; char database_password[100]; int database_port; char server_ip[100]; int server_port; } Config; ``` 接下来,我们需要编写函数来读取配置文件。以下是一个示例函数: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> void read_config_file(Config* config) { FILE* fp; char line[100]; char section[100]; char key[100]; char value[100]; fp = fopen("config.ini", "r"); if (fp == NULL) { printf("Error: could not open config file.\n"); exit(1); } while (fgets(line, sizeof(line), fp)) { // remove newline character line[strcspn(line, "\n")] = 0; if (line[0] == '[') { // new section strcpy(section, line); } else { // key-value pair sscanf(line, "%[^=]=%s", key, value); if (strcmp(section, "[database]") == 0) { if (strcmp(key, "host") == 0) { strcpy(config->database_host, value); } else if (strcmp(key, "username") == 0) { strcpy(config->database_username, value); } else if (strcmp(key, "password") == 0) { strcpy(config->database_password, value); } else if (strcmp(key, "port") == 0) { config->database_port = atoi(value); } } else if (strcmp(section, "[server]") == 0) { if (strcmp(key, "ip") == 0) { strcpy(config->server_ip, value); } else if (strcmp(key, "port") == 0) { config->server_port = atoi(value); } } } } fclose(fp); } ``` 该函数使用 fopen() 函数打开配置文件,并使用 fgets() 函数逐行读取文件内容。对于每一行,它检查行首是否为 "[",以确定当前行是否为一个新的配置部分。如果是,它将当前部分存储在 section 变量中。否则,它使用 sscanf() 函数从当前行中提取键值对,并将其存储在相应的结构体成员中。 最后,我们可以使用以下代码将配置文件的值读入内存中: ```c int main() { Config config; read_config_file(&config); printf("database host: %s\n", config.database_host); printf("database username: %s\n", config.database_username); printf("database password: %s\n", config.database_password); printf("database port: %d\n", config.database_port); printf("server ip: %s\n", config.server_ip); printf("server port: %d\n", config.server_port); return 0; } ``` 该代码调用 read_config_file() 函数,并将 Config 结构体的指针传递给它。然后,它打印每个配置值的值,以确保它们已正确读入内存中。 这就是一个简单的 Linux C 配置文件读写实例。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值