美文网首页
用C简单读取配置文件

用C简单读取配置文件

作者: 半栈 | 来源:发表于2019-03-29 13:08 被阅读0次

读取配置文件是很常见的,现在想弄一个用C简单读取配置文件的一个程序,下面是代码:

#include<stdio.h>

#include<iostream>

#include<string.h>

#include<fstream>

using namespace std;

#define LENG 1000

void fileRead(char * fname) {

    char key[LENG], value[LENG];

    int i = 0, j=0;

    int len;

    FILE *fp;

    char buf[LENG];

    fp = fopen(fname, "r");

    if (fp == NULL) {

        cout << "fail to read!" << endl;

        exit(1);

    }

    while (fgets(buf,LENG , fp) != NULL) {

        len = strlen(buf);

        int value_length=0;

        int key_length=0;

        int j1 = 0, i2 = 0, j2 = 0;

        i=0;

        while (buf[i] != '=') {                                    //等号定位

            i++;

        }

        for (j = 0; j < i; j++) {                              //关键字读取

            key[j1] = buf[j];

            j1++;

            key_length=j1;

        }

        for (j = i+1; j < len; j++) {                    //等号右边的 值读取

            value[j2] = buf[j];

            j2++;

            value_length=j2;

        }

        for (j = 0; j < key_length; j++)

            cout << key[j];

        for (j = 0; j < value_length; j++)

            cout << value[j];

    }

    fclose (fp);

}

int main() {

    char * filename = "1.txt";

    cout << endl;

    fileRead(filename);

    return 0;

}

配置文件格式如下:

SHCONFIG            = /home/wenbh/SuperCall/ShConfig.ini

DBSERVER            = 192.168.2.2

DBACCOUNT            = postgres

DBPASSWORD        = 123456  

MONITORPORT        = 23

MEETINGREMIND    = MeetingRemind.wav

读这个文件时,把等号去除掉如下:

SHCONFIG                      /home/wenbh/SuperCall/ShConfig.ini

DBSERVER                      192.168.2.2

DBACCOUNT                      postgres

DBPASSWORD                  123456  

MONITORPORT                    23

MEETINGREMIND                  MeetingRemind.wav

运行代码,如图:

相关文章

网友评论

      本文标题:用C简单读取配置文件

      本文链接:https://www.haomeiwen.com/subject/gcllbqtx.html