【C++常用API】C++读写ini文件

//创建写入ini文件
string filePath = "D:\\1.ini";//ini文件路径
string content = "要保存的内容";
WritePrivateProfileString("section1", "sec1_key1", content.c_str(), filePath.c_str());
//读取ini文件
string szValue;//存放读取的内容
GetPrivateProfileString("section1", "sec1_key1", "Default", const_cast<char*> (szValue.c_str()), 50, filePath.c_str());

以下是使用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; } ``` 以上代码仅供参考,具体实现方式可以根据实际需求进行调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值