com_slave/read_config.c

181 lines
3.7 KiB
C
Raw Permalink Normal View History

2025-02-15 13:41:40 +00:00
#include "read_config.h"
#include <string.h>
int open_config_file(simp_config_t *config, const char *filename)
{
config->fp = fopen(filename, "rw+");
if (config->fp == NULL)
{
perror("fopen");
return -1;
}
return 0;
}
void close_config_file(simp_config_t *config)
{
if (config->fp != NULL)
{
fclose(config->fp);
config->fp = NULL;
}
}
int read_config_file_u32(simp_config_t *config, const char *key, u32 *value)
{
char line[MAX_CONFIG_LINE_LEN];
char *p;
// 移动到文件头
fseek(config->fp, 0, SEEK_SET);
while (fgets(line, sizeof(line), config->fp) != NULL)
{
if (line[0] == '#' || line[0] == '\n')
{
continue;
}
// key:value
p = strstr(line, key);
if (p == NULL)
{
continue;
}
p = strchr(line, ':');
if (p == NULL)
{
continue;
}
// 去掉前面的空格
while (*p == ' ')
{
p++;
}
sscanf(p + 1, "%u", value);
return 0;
}
return -1;
}
int read_config_file_string(simp_config_t *config, const char *key, char *value, u32 len)
{
char line[MAX_CONFIG_LINE_LEN];
char *p;
// 移动到文件头
fseek(config->fp, 0, SEEK_SET);
while (fgets(line, sizeof(line), config->fp) != NULL)
{
if (line[0] == '#' || line[0] == '\n')
{
continue;
}
// key:value
p = strstr(line, key);
if (p == NULL)
{
continue;
}
p = strchr(line, ':');
if (p == NULL)
{
continue;
}
p++;
// 去掉前面的空格
while (*p == ' ')
{
p++;
}
if (*p == '"')
{
p++;
}
while (*p != '\n' && *p != '\0' && *p != '"')
{
*value = *p;
value++;
p++;
}
*value = '\0';
return 0;
}
return -1;
}
int read_config_file_float(simp_config_t *config, const char *key, float *value)
{
char line[MAX_CONFIG_LINE_LEN];
char *p;
// 移动到文件头
fseek(config->fp, 0, SEEK_SET);
while (fgets(line, sizeof(line), config->fp) != NULL)
{
if (line[0] == '#' || line[0] == '\n')
{
continue;
}
// key:value
p = strstr(line, key);
if (p == NULL)
{
continue;
}
p = strchr(line, ':');
if (p == NULL)
{
continue;
}
// 去掉前面的空格
while (*p == ' ')
{
p++;
}
sscanf(p + 1, "%f", value);
return 0;
}
return -1;
}
#if 0
int main(void)
{
simp_config_t config;
int ret = 0;
ret = open_config_file(&config, "config.temp");
if (ret)
{
printf("open config file failed\n");
return -1;
}
char uart_dev[MAX_CONFIG_LINE_LEN];
ret = read_config_file_string(&config, "uart_device", uart_dev, MAX_CONFIG_LINE_LEN);
if (ret)
{
printf("read uart_device failed\n");
return -1;
}
printf("uart_device:%s\n", uart_dev);
u32 baudrate;
ret = read_config_file_u32(&config, "uart_baudrate", &baudrate);
if (ret)
{
printf("read baudrate failed\n");
return -1;
}
printf("baudrate:%u\n", baudrate);
float uart_float;
ret = read_config_file_float(&config, "uart_float", &uart_float);
if (ret)
{
printf("read uart_float failed\n");
return -1;
}
printf("uart_float:%f\n", uart_float);
close_config_file(&config);
}
#endif