文本如下:yb.txt
AA 23
BB 32
CC 22
代码如下:
#include<stdio.h> #define CHAR_LEN 20 char *scan_config(char *keyword) { int n,match; FILE *fp; char keybuf[CHAR_LEN]=""; char line[CHAR_LEN]=""; char *valbuf; valbuf = malloc(CHAR_LEN*sizeof(char)); memset(valbuf,0,sizeof(valbuf)); if((fp = fopen("yb.txt","r"))==NULL) printf("Open yb.txt error "); match = 0; while(fgets(line,10,fp) != NULL) { n = sscanf(line,"%s %s",keybuf,valbuf); if( n ==2 && strcmp(keyword,keybuf) ==0 ) { match = 1; break; } } fclose(fp); if(match != 0) { return (valbuf); } else return (NULL); } int main(int argc,char **argv) { printf("result = %s ",scan_config(argv[1])); return 0; }