C语言读取配置文件

来源:互联网 发布:cms监控软件下载 编辑:程序博客网 时间:2024/05/17 03:40

配置文件:

a.txt

1
2
3
# ip=sadf
  ip =192.168.246.22
  dns     =                   218.85.157.99

读取规则:

1 以‘#’开头的为注释,不读取

2 空行也不读取

3 ‘=’两边可以有空格



这里先讲下要用到的知识点

1 断言的使用

assert() 宏用法
注意:assert是宏,而不是函数。在C的assert.h头文件中。
assert宏的原型定义在<assert.h>中,其作用是如果它的条件返回错误,则终止程序执行,原型定义:
#include <assert.h>void assert( int expression );
assert的作用是先计算表达式expression,如果其值为假(即为0),那么它先向标准错误流stderr打印一条出错信息,然后通过调用abort来终止程序运行;否则,assert()无任何作用。宏assert()一般用于确认程序的正常操作,其中表达式构造无错时才为真值。完成调试后,不必从源代码中删除assert()语句,因为宏NDEBUG有定义时,宏assert()的定义为空。


2 strtok()--字符串分割函数的使用

头文件:#include <string.h>

定义函数:char * strtok(char *s, const char *delim);

函数说明:strtok()用来将字符串分割成一个个片段.

参数s 指向欲分割的字符串, 参数delim 则为分割字符串,

当strtok()在参数s 的字符串中发现到参数delim 的分割字符时则会将该字符改为\0 字符.

在第一次调用时,strtok()必需给予参数s 字符串, 往后的调用则将参数s 设置成NULL.

每次调用成功则返回下一个分割后的字符串指针.


返回值:返回下一个分割后的字符串指针, 如果已无从分割则返回NULL.



接下来就是具体代码了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <ctype.h>
/*   删除左边的空格   */
char * del_left_trim(char *str) {
    assert(str != NULL);
    for (;*str != '\0' && isblank(*str) ; ++str);
    return str;
}
/*   删除两边的空格   */
char * del_both_trim(char * str) {
    char *p;
    char * szOutput;
    szOutput = del_left_trim(str);
    for (p = szOutput + strlen(szOutput) - 1; p >= szOutput && isblank(*p);
            --p);
    *(++p) = '\0';
    return szOutput;
}
/*主函数*/
int main(int argc, char **argv) {
    FILE * fp = NULL;
   /*打开配置文件a.txt*/
    fp = fopen("./a.txt""r");
   /*緩沖區*/
    char buf[64];
    char s[64];
    /*分割符*/
    char * delim = "=";
    char * p;
    char ch;
     while (!feof(fp)) {
        if ((p = fgets(buf, sizeof(buf), fp)) != NULL) {
            strcpy(s, p);
            ch=del_left_trim(s)[0];
           /*判断注释 空行,如果是就直接下次循环*/
            if (ch == '#' || isblank(ch) || ch=='\n')
                continue;
          /*分割字符串*/
            p=strtok(s, delim);
            if(p)
            printf("%s", del_both_trim(p));
            while ((p = strtok(NULL, delim)))
            printf("%s ", del_both_trim(p));
            printf("\n");
        }
    }
    return 0;
}


查看结果:

1
2
3
ip192.168.246.22
      
dns218.85.157.99


最基本的读取配置文件,就这样了!

本文出自 “技术在于坚持” 博客,请务必保留此出处http://minilinux.blog.51cto.com/4499123/1309779

0 0