2018年4月12日 星期四

[C] read value from file

#include <stdio.h>
#include <stdlib.h>

int GetCfgSettings(char *f)
{
    FILE *fp;
    char cmd[50]= {0};
    char ret[20]= {0};
    int vol = 0;

    strncpy(cmd, f, sizeof(cmd)-1);
    cmd[sizeof(cmd)-1] = '\0';
    fp = popen(cmd, "r");

    if (fp != NULL) {
        fgets(ret, sizeof(ret)-1, fp);
        ret[sizeof(ret)-1] = '\0';
        pclose(fp);

        vol = atoi(ret);
        return vol;
    } else
        return 0;
}

void main ()
{
    int a;
    a= GetCfgSettings("cat /tmp/a.txt");
    printf("a = %d",a);
}

/*
 * Execute this command.
 * if a.txt have 123 inside.
 *
 * ./a.out will show  a = 123
 *
 * */

0 意見:

張貼留言