c语言 读写ini文件 代码
时间: 2023-09-26 15:14:21 浏览: 53
以下是使用C语言读写ini文件的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINE_SIZE 1024
// 定义一个结构体,用于存储读取到的ini文件中的键值对
typedef struct {
char key[MAX_LINE_SIZE];
char value[MAX_LINE_SIZE];
} KeyValue;
// 定义一个函数,用于去除字符串两端的空格和换行符
void trim(char *str) {
int len = strlen(str);
while (len > 0 && (str[len - 1] == ' ' || str[len - 1] == '\n' || str[len - 1] == '\r')) {
str[--len] = '\0';
}
int start = 0;
while (str[start] && (str[start] == ' ' || str[start] == '\n' || str[start] == '\r')) {
++start;
}
if (start > 0) {
memmove(str, str + start, len - start + 1);
}
}
// 定义一个函数,用于读取ini文件中的键值对
int read_ini_file(const char *filename, KeyValue *kv, int max_count) {
FILE *fp = fopen(filename, "r");
if (fp == NULL) {
return -1;
}
int count = 0;
char line[MAX_LINE_SIZE];
while (fgets(line, MAX_LINE_SIZE, fp) != NULL) {
trim(line);
if (strlen(line) == 0) {
continue;
}
if (line[0] == '[' && line[strlen(line) - 1] == ']') {
// 这是一个节(Section)的名称,忽略掉
continue;
}
char *p = strchr(line, '=');
if (p == NULL) {
// 没有找到等号,忽略掉
continue;
}
*p++ = '\0';
trim(line);
trim(p);
strncpy(kv[count].key, line, MAX_LINE_SIZE - 1);
strncpy(kv[count].value, p, MAX_LINE_SIZE - 1);
++count;
if (count >= max_count) {
// 配对的键值对数量已经达到了最大值,停止读取
break;
}
}
fclose(fp);
return count;
}
// 定义一个函数,用于写入ini文件中的键值对
int write_ini_file(const char *filename, KeyValue *kv, int count) {
FILE *fp = fopen(filename, "w");
if (fp == NULL) {
return -1;
}
for (int i = 0; i < count; ++i) {
fprintf(fp, "%s=%s\n", kv[i].key, kv[i].value);
}
fclose(fp);
return 0;
}
int main() {
// 读取ini文件中的键值对,并打印出来
KeyValue kv[1024];
int count = read_ini_file("config.ini", kv, 1024);
for (int i = 0; i < count; ++i) {
printf("%s=%s\n", kv[i].key, kv[i].value);
}
// 修改键值对
for (int i = 0; i < count; ++i) {
if (strcmp(kv[i].key, "name") == 0) {
strcpy(kv[i].value, "Alice");
break;
}
}
// 写入ini文件
write_ini_file("config.ini", kv, count);
return 0;
}
```
以上代码仅供参考,具体实现方式可以根据实际需求进行调整。