代码改变世界

取文本索引所执向的值(简单)

2015-09-18 15:41  夏洛克·福尔摩斯  阅读(346)  评论(0编辑  收藏  举报

 

文本如下: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\n");
    
    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\n",scan_config(argv[1]));
    return 0;
}