您可以通过基础 c 文件操作(fopen/fclose/fgets)来完成,然后使用字符串操作来中断和剪切读取的字符串(strtok 是最好的例子)。
根据您的要求,以下源代码不完整。但可以肯定的是,它会为您提供一些基本的想法。要执行此代码,请创建名为 temp.config 的文件并将您的文件包含在其中。
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include<stdint.h>
#define MAXLEN 1024
#define CONFIG_FILE "temp.config"
/*
* remove trailing and leading whitespace
*/
static inline char *
trim (char * s)
{
/* Initialize start, end pointers */
char *s1 = s, *s2 = &s[strlen (s) - 1];
/* Trim and delimit right side */
while ( (isspace (*s2)) && (s2 >= s1) )
s2--;
*(s2+1) = '\0';
/* Trim left side */
while ( (isspace (*s1)) && (s1 < s2) )
s1++;
/* Copy finished string */
strcpy (s, s1);
return s;
}
inline bool
parse_config ( ){
#ifdef DEBUG
fprintf(stdout,"__parse_config__\n");
#endif
char *s, buff[MAXLEN];
char *temp1,*temp2;
FILE *fp = fopen (CONFIG_FILE, "r");
if (fp == NULL){
fprintf(stderr,"Not able to open file\n");
return false;
}
/* Read next line */
while ( ( (s = fgets (buff, sizeof buff, fp)) != NULL) ){
/* Skip blank lines and comments */
if (buff[0] == '\n' || buff[0] == '#')
continue;
/* Parse name/value pair from line */
char name[MAXLEN], value[MAXLEN];
s = strtok (buff, " ");
if (s==NULL)
continue;
else
strncpy (name, s, MAXLEN);
s = strtok (NULL, " ");
if (s==NULL)
continue;
else
strncpy (value, s, MAXLEN);
trim (value);
/* you can use a switch case*/
if (strcmp(name, "LOAD")==0){
fprintf(stdout,"%s\n",name);
temp1 = strtok(value,",");
fprintf(stdout,"%s\n",value);
//this is the logic.. rest you have to implement.
} if (strcmp(name, "LOADI")==0){
fprintf(stdout,"%s\n",name);
temp1 = strtok(value,",");
fprintf(stdout,"%s\n",value);
}
}
fclose(fp);
return true;
}
int main(){
parse_config();
return 0;
}
输出:
root@suman-OptiPlex-380:/home/suman/poc# ./a.out
LOAD
A1
LOADI
R1
注意:我刚刚打印了输出,你可以存储它。