学习/proc/sys下配置的存储方式,个人总结有以下优点:
第一:按照用途分类,易于理解,逻辑清楚
第二:树形结构存储,方便查找,易于修改
第三:一个文件存储一个配置,易于远程修改,如果你把几十个配置存进一个文件中,要远程修改几十台,那是很头疼的事情,如果一个文件一个配置的话,那么只需要如下方式:
- ssh root@10.10.10.10 --cmd "echo 12345 >/etc/cmtools/sys/port"
- ssh root@111.11.11.11 --cmd "echo local5 > /etc/cmtools/syslog/facility"
就把端口值修改为12345了。很方便.
代码功能如下:
如果能够找到配置,就读取出来,返回。
如果不存在,就创建文件,把默认值存下来,并且返回默认值。
缺点:不支持多线程,函数中用了static char []
代码如下:
- //created by duanjigang@2011-06-16
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <libgen.h>
- #include <string.h>
- char* get_conf(const char* path, const char* dft)
- {
- static char szret[256] = {0};
- char szpath[512] = {0}, szpath1[512] = {0};
- memset (szret, 0, sizeof(szret));
- if (strlen(path) > 512)
- {
- printf ("path too long %d\n", strlen(path));
- sprintf (szret, dft);
- return szret;
- }
- sprintf (szpath, "/etc/%s", path);
- int len = strlen(szpath);
- int i = 0;
- for (i = 0; i < len; i++)
- {
- if (szpath[i] == '.') szpath[i] = '/';
- }
- //printf ("%s:%d\n", szpath, strlen(szpath));
- if (access(szpath, R_OK))
- {
- char szdir[512] = {0};
- strcpy (szpath1, szpath);
- sprintf (szdir, "mkdir -pv %s", dirname(szpath1));
- system (szdir);
- FILE * fp = fopen (szpath, "w");
- if (fp)
- {
- fprintf (fp, "%s", dft);
- fclose (fp);
- }
- sprintf (szret, dft);
- return szret;
- }
- int ok = 1;
- FILE * fp = fopen (szpath, "r");
- if (fp)
- {
- if (fgets(szret, sizeof(szret), fp))
- {
- fclose (fp);
- return szret;
- }else
- {
- ok = 0;
- }
- }else ok = 0;
-
- if (!ok)
- {
- FILE * fp = fopen (szpath, "w");
- if (fp)
- {
- fprintf (fp, "%s", dft);
- fclose (fp);
- }
- sprintf (szret, dft);
- }
- return szret;
- }
- int main()
- {
- printf ("cmtools.test_conf.var1=%s\n", get_conf("cmtools.test_conf.var1", "value1"));
- printf ("cmtools.test_conf.var2=%s\n", get_conf("cmtools.test_conf.var2", "value2"));
- printf ("cmtools.test_conf1.var1=%s\n", get_conf("cmtools.test_conf.var1", "value1"));
- printf ("cmtools.test_conf.var1=%s\n", get_conf("cmtools.test_conf.var1", "aaa"));
- printf ("cmtools.test_conf.var2=%s\n", get_conf("cmtools.test_conf.var2", "bbb"));
- printf ("cmtools.test_conf1.var1=%s\n", get_conf("cmtools.test_conf1.var1", "ccc"));
- return 1;
- }
阅读(2565) | 评论(0) | 转发(0) |