读取环境变量并利进行文件的解析

同样以触摸屏的适配器tslib中的函数进行描述,如何从当前的环境变量中读取一个环境变量,并利进行文件的解析,
下面先对几个程序看几个将要用到的函数:

 FILE * fopen(const char * path,const char * mode);
  函数功能: 打开一个文件
  函数原型:FILE * fopen(const char * path,const char * mode);
  相关函数:open,fclose,fopen_s[1] ,_wfopen
  所需库: <stdio.h>
  返回值: 文件顺利打开后,指向该流的文件指针就会被返回。如果文件打开失败则返回NULL,并把错误代码存在errno 中。
  一般而言,打开文件后会作一些文件读取或写入的动作,若打开文件失败,接下来的读写动作也无法顺利进行,所以一般在fopen()后作错误判断及处理。
 (参考百度百科)

  char *strdup(char *s);
  功能:复制字符串s
  说明:返回指向被复制的字符串的指针,所需空间由malloc()分配且可以由free()释放。

 char *strsep(char **stringp, const char *delim);
  功能:分解字符串为一组字符串。

 strcasecmp(忽略大小写比较字符串)
  相关函数 bcmp,memcmp,strcmp,strcoll,strncmp
  表头文件 #include<string.h>
  定义函数 int strcasecmp (const char *s1, const char *s2);
  函数说明 strcasecmp()用来比较参数s1和s2字符串,比较时会自动忽略大小写的差异。
 返回值 若参数s1和s2字符串相同则返回0。s1长度大于s2长度则返回大于0 的值,s1 长度若小于s2 长度则返回小于0的值。

int ts_config(struct tsdev *ts)
{
char buf[BUF_SIZE], *p;
FILE
*f;
int line = 0;
int ret = 0;

char *conffile;

if( (conffile = getenv("TSLIB_CONFFILE")) == NULL) {
conffile
= strdup (TS_CONF);
}

f
= fopen(conffile, "r");
if (!f) {
perror(
"Couldnt open tslib config file");
return -1;
}

buf[BUF_SIZE
- 2] = '\0';
while ((p = fgets(buf, BUF_SIZE, f)) != NULL) {
char *e;
char *tok;
char *module_name;

line
++;

/* Chomp */
e
= strchr(p, '\n');
if (e) {
*e = '\0';
}

/* Did we read a whole line? */
if (buf[BUF_SIZE - 2] != '\0') {
ts_error(
"%s: line %d too long\n", conffile, line);
break;
}

tok
= strsep(&p, " \t");

/* Ignore comments or blank lines.
* Note: strsep modifies p (see man strsep)
*/

if (p==NULL || *tok == '#')
continue;

/* Search for the option. */
if (strcasecmp(tok, "module") == 0) {
module_name
= strsep(&p, " \t");
ret
= ts_load_module(ts, module_name, p);
}
else if (strcasecmp(tok, "module_raw") == 0) {
module_name
= strsep(&p, " \t");
ret
= ts_load_module_raw(ts, module_name, p);
}
else {
ts_error(
"%s: Unrecognised option %s:%d:%s\n", conffile, line, tok);
break;
}
if (ret != 0) {
ts_error(
"Couldnt load module %s\n", module_name);
break;
}
}

if (ts->list_raw == NULL) {
ts_error(
"No raw modules loaded.\n");
ret
= -1;
}

fclose(f);

return ret;
}
原文地址:https://www.cnblogs.com/hoys/p/2026817.html