关闭

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

638人阅读 评论(0) 收藏 举报
分类:
#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;
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:1048195次
    • 积分:18292
    • 等级:
    • 排名:第521名
    • 原创:741篇
    • 转载:523篇
    • 译文:0篇
    • 评论:105条
    最新评论