除了json,xml,protobuf等成体系的配置文件外,简单的文本格式“key value”的配置文件也在很多开源项目中存在,这种配置文件的好处是简单、易于理解和编辑。
#include <stdio.h>
#include <string.h>
#define MAX_LINE_LENGTH 1024
void ParseConfig(const char *filePath)
{
FILE *file = fopen(filePath, "r");
if (file == NULL)
{
perror("Error opening file");
return;
}
char line[MAX_LINE_LENGTH];
while (fgets(line, sizeof(line), file) != NULL)
{
// 去掉行末尾的换行符
line[strcspn(line, "\r\n")] = '\0';
// 忽略注释和空行
if (line[0] == '#' || line[0] == '\0')
{
continue;
}
// 解析配置项
char *key = strtok(line, " \t");
char *value = strtok(NULL, " \t");
if (key != NULL && value != NULL)
{
printf("%s %s\n", key, value);
}
}
fclose(file);
}
int main()
{
const char *filePath = "config.txt";
ParseConfig(filePath);
return 0;
}
- 更新分割线
- 读写
/* ConfigWrite.c */
#include <stdio.h>
#include <stdint.h>
#define MAX_KEY_LENGTH 50
#define MAX_VALUE_LENGTH 100
#define MAX_ENTRIES 100
typedef struct {
char key[MAX_KEY_LENGTH];
char value[MAX_VALUE_LENGTH];
}ConfigEntry;
void WriteConfig(const char *filePath, const ConfigEntry *entries, int16_t numEntries)
{
FILE *file = fopen(filePath, "w");
if (file == NULL)
{
perror("Error opening file for writing");
return;
}
for (int16_t i = 0; i < numEntries; ++i)
{
fprintf(file, "%s %s\n", entries[i].key, entries[i].value);
}
fclose(file);
}
int main()
{
ConfigEntry configEntries[MAX_ENTRIES] =
{
{"Key1", "Value1"},
{"Key2", "Value2"},
{"#Key3", "Value3"},
// Add more...
};
const int16_t numEntries = sizeof(configEntries) / sizeof(ConfigEntry);
const char *filePath = "output_config.txt";
WriteConfig(filePath, configEntries, numEntries);
return 0;
}
/* ConfigRead.c */
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#define MAX_KEY_LENGTH 50
#define MAX_VALUE_LENGTH 100
#define MAX_ENTRIES 100
typedef struct {
char key[MAX_KEY_LENGTH];
char value[MAX_VALUE_LENGTH];
} ConfigEntry;
int16_t ParseConfig(const char *filePath, ConfigEntry *configEntries)
{
FILE *file = fopen(filePath, "r");
if (file == NULL)
{
perror("Error opening file");
return 0;
}
int16_t count = 0;
char line[MAX_ENTRIES];
while (fgets(line, sizeof(line), file) != NULL)
{
// 去掉行末尾的换行符
line[strcspn(line, "\r\n")] = '\0';
// 忽略注释和空行
if (line[0] == '#' || line[0] == '\0')
{
continue;
}
// 解析配置项
char *key = strtok(line, " \t");
char *value = strtok(NULL, " \t");
// char *value2 = strtok(NULL, " \t");
if (key != NULL && value != NULL && count < MAX_ENTRIES)
{
strncpy(configEntries[count].key, key, sizeof(configEntries[count].key) - 1);
strncpy(configEntries[count].value, value, sizeof(configEntries[count].value) - 1);
++count;
}
}
fclose(file);
return count;
}
int main()
{
const char *filePath = "output_config.txt";
ConfigEntry configEntries[MAX_ENTRIES];
int16_t numPairs = ParseConfig(filePath, configEntries);
for (int16_t i = 0; i < numPairs; ++i)
{
printf("%s %s\n", configEntries[i].key, configEntries[i].value);
}
return 0;
}