嵌入式 简单的读取文件并打印指定字符串的值

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>

#ifdef __DEBUG__
    #define msg_print(...) printf(__VA_ARGS__)
#else
    #define msg_print(...)
#endif

#define CONF_FILE_PATH "./ipnc_conf.conf"
#define MAX_VALUE_LEN 32
#define ARGV_NOT_EXIST 2
#define ARGV_EXIST 5

#define DEFALUT_JIPNC_ID "jipnc00000000005"
#define DEFALUT_JIPNC_KEY "12345678"
#define DEFALUT_JIPNC_DEVICE_TYPE "30"


int joseph_read_conf(const char *key, char *value);
int joseph_create_conf(const char *id, const char *key, const char *device_type, int flag);

int joseph_create_conf(const char *id, const char *key, const char *device_type, int flag)
{
   int conf_fd;
   int ret;
   char buffer[1024] = {0};
   
   if(flag == ARGV_NOT_EXIST){
   	conf_fd = open(CONF_FILE_PATH, O_RDONLY | O_EXCL, 777);
	msg_print("conf_fd = %d\n",conf_fd);
   	if(conf_fd > 0){
       	    close(conf_fd);
       	    return 0;
   	}
   }

   conf_fd = open(CONF_FILE_PATH, O_WRONLY | O_CREAT | O_TRUNC, 777);
   sprintf(buffer, "ipnc_id %s\nipnc_key %s\ndevice_type %s\n", id, key, device_type);
   ret = write(conf_fd, buffer, 1024);
   msg_print("ret = %d\nbuffer = %s", ret, buffer);

   close(conf_fd);
   return 0;

}

int joseph_read_conf(const char *key, char *value)
{
    FILE *stream = NULL;
    char cmd[64] = {0};

    if(NULL == key || 0 == strlen(key)){
    	msg_print("invalid parameter!\n");
	return -1;
    }

    sprintf(cmd, "cat %s | awk '/%s/{print $2}'", CONF_FILE_PATH, key);
    msg_print("cmd = %s\n",cmd);

    stream = popen(cmd,"r");

    if(fread(value, sizeof(char), MAX_VALUE_LEN, stream) <= 0){
    	pclose(stream);
	return -1;
    }
    strcpy(value + strlen(value) - 1, "\0");
    msg_print("%s = %s\n", key, value);
    
    pclose(stream);
    system("rm -rf ./ipnc_conf.conf");
    return 0;
}

int main(int argc,char *argv[])
{
    char value[32] = {0};

    //if(argc != 1 || argc != 4)
    //{
    //	printf("invalid parameter!\n");
    //	return -1;
    //}
#if 1
    if(ARGV_NOT_EXIST == argc)
    	joseph_create_conf(DEFALUT_JIPNC_ID, DEFALUT_JIPNC_KEY ,DEFALUT_JIPNC_DEVICE_TYPE, ARGV_NOT_EXIST);
    else if(ARGV_EXIST == argc)
    	joseph_create_conf(argv[1], argv[2] ,argv[3], ARGV_EXIST);
    else{
    	printf("invalid parameter!\n");
    	return -1;
    }
#endif 
    joseph_read_conf("ipnc_id", value);
    printf("%s = %s\n", "ipnc_id", value);

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值