Linux C语言 读写配置文件
时间: 2023-07-16 21:13:46 浏览: 228
在Linux C语言中,读写配置文件通常使用INI文件格式。INI文件格式是一种简单的文本文件格式,其中键值对以节(section)的形式组织,并使用方括号([])将节名括起来。
以下是一个示例INI文件:
```
[Section1]
key1=value1
key2=value2
[Section2]
key3=value3
key4=value4
```
使用C语言读取INI文件的步骤如下:
1. 打开INI文件并读入内容。
2. 解析INI文件内容,将键值对存储到内存中的数据结构中。
3. 使用存储的键值对执行相应的操作。
以下是一个简单的例子:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINE_LEN 1024
#define MAX_SECTION_LEN 256
#define MAX_KEY_LEN 256
#define MAX_VALUE_LEN 256
typedef struct {
char section[MAX_SECTION_LEN];
char key[MAX_KEY_LEN];
char value[MAX_VALUE_LEN];
} config_item_t;
int parse_config_file(const char* filename, config_item_t** items, int* count) {
FILE* fp = fopen(filename, "r");
if (!fp) {
return -1;
}
char line[MAX_LINE_LEN];
config_item_t* item = NULL;
int item_count = 0;
while (fgets(line, MAX_LINE_LEN, fp)) {
// 去掉行末换行符
char* p = strchr(line, '\n');
if (p) *p = '\0';
// 去掉行首空格
p = line;
while (*p == ' ') ++p;
// 解析节
if (*p == '[') {
char* q = strchr(p, ']');
if (!q) {
fclose(fp);
return -1;
}
*q = '\0';
item = NULL;
continue;
}
// 解析键值对
if (item) {
char* q = strchr(p, '=');
if (!q) continue; // 忽略无效行
*q = '\0';
strcpy(item->key, p);
strcpy(item->value, q + 1);
++item;
} else {
// 新建配置项
item = (config_item_t*)realloc(item, (item_count + 1) * sizeof(config_item_t));
if (!item) {
fclose(fp);
return -1;
}
strcpy(item->section, p);
item->key[0] = '\0';
item->value[0] = '\0';
items[item_count++] = item;
}
}
fclose(fp);
*count = item_count;
return 0;
}
void free_config_items(config_item_t** items, int count) {
for (int i = 0; i < count; ++i) {
free(items[i]);
}
free(items);
}
int main() {
config_item_t* items[100];
int count = 0;
if (parse_config_file("test.ini", items, &count) == 0) {
for (int i = 0; i < count; ++i) {
printf("[%s]\n", items[i]->section);
printf("%s=%s\n", items[i]->key, items[i]->value);
}
}
free_config_items(items, count);
return 0;
}
```
该程序使用`parse_config_file`函数读取INI文件并解析内容,将每个节的键值对存储到一个`config_item_t`结构体中。最后,在`main`函数中遍历所有配置项并输出。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)