配置文件读取的n种方法
2007-01-28 15:57
525 查看
摘要
使用了下面5种方法来读取配置文件:1)字符串读写操作;2)xml解析配置文件;3)stl的读取配置文件封装类,很繁杂,但在大型配置文件中比较有用;4)shell语言的字符串匹配,这是最简单的;5)将1与4结合,shell与c的嵌套使用。1字符串读写操作
测试文件[test.init]#ini for path
[path]
dictfile = /home/tmp/dict.dat
inputfile= /home/tmp/input.txt
outputfile= /home/tmp/output.txt
#ini for exe
[exe]
user= winter //user name
passwd= 1234567 #pass word
database= mydatabase
int main(int argc, char *argv[])
...{
FILE* file;
char input[100];
unsigned short port;
//fopen file to read
//...
while(1)
...{
char* s =fgets(input, 100, file);
if(s == NULL) break;
if( (!strchr(input, '#') || (!strchr(input, '[') ) continue;
if(!strncasecmp(input, "port", 4))
...{
port = atoi(strchr(input, ''));
}
if() //...
}
return 0;
}
2 xml解析配置文件法
基本思路:使用libxml2的一些tree解析函数,如:xmlReadFile, xmlDocGetRootElement, xmlStrcmp, xmlNodeGetContent。使用了一些属性:name(结点的名称), child(子结点), next(下一个结点)...具体可参考本人另一篇blog: http://blog.csdn.net/wqf363/archive/2006/11/18/1394600.aspx
3 stl的读取配置文件封装类
基本思路:读取文件,将某个字符串开头的读入map里的key, 在其value值把其它字符串读入;读取时,查询key, 就获取到与key对应的value了。4 shell的读取配置文件
# user.conf: configure file for user# username age sex country
tom 20 male us
chen 22 female cn
例如,我们要获取 tom 的性别
可以用脚本这样来实现:
cat user.conf | awk '/^tom[[:blank:]]+/ {print $3}'
5 shell与C的嵌套使用
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
static int my_system(const char* pCmd, char* pResult, int size);
int main(void)
...{
char result[1025];
my_system("cat user.conf | awk '/^tom[[:blank:]]+/ {print $3}'", result, 1025);
printf("the result is: %s ", result);
return 0;
}
static int my_system(const char* pCmd, char* pResult, int size)
...{
int fd[2];
int pid;
int count;
int left;
char* p = 0;
int maxlen = size-1;
memset(pResult, 0, size);
if(pipe(fd))
...{
return -1;
}
if((pid = fork()) == 0)
...{// chile process
int fd2[2];
if(pipe(fd2))
...{
return -1;
}
close(1);
dup2(fd2[1],1);
close(fd[0]);
close(fd2[1]);
system(pCmd);
read(fd2[0], pResult, maxlen);
pResult[strlen(pResult)-1] = 0;
write(fd[1], pResult, strlen(pResult));
close(fd2[0]);
exit(0);
}
// parent process
close(fd[1]);
p = pResult;
left = maxlen;
while((count = read(fd[0], p, left))) ...{
p += count;
left -= count;
if(left == 0)
break;
}
close(fd[0]);
return 0;
}
[denny@localhost testforc]$ ./a.out
the result is: male
相关文章推荐
- Shell实现读取ini格式配置文件方法
- java中读取配置文件的方法fileSystemXmlapplicationContext与classPathXmlApplicationContext
- .Net配置文件读取及修改方法封装(未加密)
- JavaWeb读取配置文件的四种方法
- 多个Spring配置文件时,读取方法
- DotNet调用WindowsAPI读取INI配置文件方法
- vc中读取配置文件的方法
- ASP .NET CORE 读取配置文件的方法
- Java读取配置文件的几种方法
- java中读取配置文件的方法
- ibatis读取配置文件取得SqlMapClient实例的方法
- java读取配置文件的几种方法
- Spring读取配置文件的方法
- play读取配置文件的方法
- spring 读取配置文件的方法
- 读取Spring的配置文件applicationContext.xml的5种方法
- 读取spring配置文件的方法(spring读取资源文件)
- Python实现读取Properties配置文件的方法
- Java读取properties配置文件时,中文乱码解决方法
- java读取配置文件的几种方法