c++:读写ini文件(附完整源码)

时间: 2023-07-03 13:02:15 浏览: 83
### 回答1: 以下是使用C语言读写ini文件的完整源代码: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_LINE_LENGTH 256 int getValueFromIniFile(const char* filename, const char* section, const char* key, char* value) { FILE* file = fopen(filename, "r"); if (file == NULL) { printf("Failed to open file %s\n", filename); return 0; } char currentSection[MAX_LINE_LENGTH] = ""; char line[MAX_LINE_LENGTH]; int foundSection = 0; while (fgets(line, sizeof(line), file) != NULL) { // Remove newline character at the end line[strcspn(line, "\n")] = '\0'; // Check if it is a section if (line[0] == '[' && line[strlen(line)-1] == ']') { strncpy(currentSection, line+1, strlen(line)-2); currentSection[strlen(line)-2] = '\0'; if (strcmp(currentSection, section) == 0) { foundSection = 1; } else { foundSection = 0; } } else if (foundSection) { // Check if it is the desired key char* delimiter = strchr(line, '='); if (delimiter != NULL) { // Split the line into key and value char currentKey[MAX_LINE_LENGTH] = ""; strncpy(currentKey, line, delimiter - line); currentKey[delimiter - line] = '\0'; if (strcmp(currentKey, key) == 0) { strncpy(value, delimiter + 1, MAX_LINE_LENGTH); value[strcspn(value, "\n")] = '\0'; // Remove newline character fclose(file); return 1; } } } } fclose(file); return 0; } int setValueToIniFile(const char* filename, const char* section, const char* key, const char* value) { FILE* file = fopen(filename, "r"); if (file == NULL) { printf("Failed to open file %s\n", filename); return 0; } // Create a temporary file for writing FILE* tempFile = fopen("temp.ini", "w"); if (tempFile == NULL) { printf("Failed to create temporary file\n"); fclose(file); return 0; } char currentSection[MAX_LINE_LENGTH] = ""; char line[MAX_LINE_LENGTH]; int foundSection = 0; int keyFoundInSection = 0; int valueWritten = 0; while (fgets(line, sizeof(line), file) != NULL) { // Check if it is a section if (line[0] == '[' && line[strlen(line)-1] == ']') { strncpy(currentSection, line+1, strlen(line)-2); currentSection[strlen(line)-2] = '\0'; if (strcmp(currentSection, section) == 0) { foundSection = 1; } else { foundSection = 0; } fprintf(tempFile, "%s", line); } else if (foundSection) { // Check if it is the desired key char* delimiter = strchr(line, '='); if (delimiter != NULL) { // Split the line into key and value char currentKey[MAX_LINE_LENGTH] = ""; strncpy(currentKey, line, delimiter - line); currentKey[delimiter - line] = '\0'; if (strcmp(currentKey, key) == 0) { fprintf(tempFile, "%s=%s\n", key, value); keyFoundInSection = 1; valueWritten = 1; } else { fprintf(tempFile, "%s", line); } } else { fprintf(tempFile, "%s", line); } } else { fprintf(tempFile, "%s", line); } } // If the key is not found, append it at the end of the section if (!keyFoundInSection) { fprintf(tempFile, "%s=%s\n", key, value); valueWritten = 1; } fclose(file); fclose(tempFile); // Replace the original file with the updated temporary file if (valueWritten) { remove(filename); rename("temp.ini", filename); } else { remove("temp.ini"); } return 1; } int main() { // 读取ini文件 char value[MAX_LINE_LENGTH]; if (getValueFromIniFile("example.ini", "Section1", "Key1", value)) { printf("Value found: %s\n", value); } else { printf("Value not found\n"); } // 写入ini文件 if (setValueToIniFile("example.ini", "Section1", "Key1", "NewValue")) { printf("Value updated\n"); } else { printf("Failed to update value\n"); } return 0; } ``` 以上代码为一个简单的读写ini文件的示例。通过`getValueFromIniFile`函数可以从指定的ini文件中获取指定的section和key的值,通过`setValueToIniFile`函数可以更新或添加ini文件中指定section和key的值。可根据实际需要修改和使用此代码。请确保在使用前要确保文件存在且有读写权限。 ### 回答2: ini文件是一种常见的文本文件格式,用于存储配置信息。读写ini文件可以通过解析文件的内容来获取配置项的值,也可以通过修改文件中的值来修改配置项。 以下是一个简单的读写ini文件的示例代码: ```python import configparser # 创建一个ConfigParser对象 config = configparser.ConfigParser() # 读取ini文件 config.read('config.ini') # 获取配置项的值 value = config.get('section_name', 'key_name') # section_name为节名,key_name为键名 # 修改配置项的值 config.set('section_name', 'key_name', 'new_value') # section_name为节名,key_name为键名,new_value为新值 # 保存修改后的ini文件 with open('config.ini', 'w') as configfile: config.write(configfile) ``` 在这个示例代码中,首先通过导入`configparser`模块创建了一个`ConfigParser`对象。然后使用`read()`方法读取了名为`config.ini`的ini文件。 通过调用`get()`方法可以获取`config.ini`文件中`section_name`节下`key_name`键的值。 通过调用`set()`方法可以将`section_name`节下`key_name`键的值修改为`new_value`。 最后,可以使用`write()`方法将修改后的配置信息写入到`config.ini`文件中。 需要注意的是,以上代码只是一个简单的示例,实际使用时需要根据具体的需求和ini文件的结构来进行相应的修改和处理。 ### 回答3: 以下是一个使用C语言读写ini文件的完整源码: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_LINE_SIZE 256 // 读取ini文件 int readIniFile(const char* filename, const char* section, const char* key, char* value) { FILE* file = fopen(filename, "r"); if (file == NULL) { printf("无法打开ini文件\n"); return -1; } char line[MAX_LINE_SIZE]; char currentSection[MAX_LINE_SIZE]; char currentKey[MAX_LINE_SIZE]; int foundSection = 0; int foundKey = 0; while (fgets(line, MAX_LINE_SIZE, file) != NULL) { // 移除换行符 line[strcspn(line, "\n")] = '\0'; // 处理注释和空行 if (line[0] == '#' || line[0] == '\0') { continue; } // 处理section if (line[0] == '[') { if (foundSection) { printf("找到了指定的section,但没有找到指定的key\n"); return -1; } sscanf(line, "[%[^]]", currentSection); if (strcmp(currentSection, section) == 0) { foundSection = 1; } } else if (foundSection) { sscanf(line, "%[^= ] = %[^\n]", currentKey, value); if (strcmp(currentKey, key) == 0) { foundKey = 1; break; } } } fclose(file); if (foundSection && foundKey) { return 0; } else { printf("没有找到指定的section或key\n"); return -1; } } // 写入ini文件 int writeIniFile(const char* filename, const char* section, const char* key, const char* value) { FILE* file = fopen(filename, "a"); if (file == NULL) { printf("无法打开ini文件\n"); return -1; } fprintf(file, "\n[%s]\n%s = %s\n", section, key, value); fclose(file); return 0; } int main() { char value[MAX_LINE_SIZE]; // 读取ini文件 if (readIniFile("config.ini", "section1", "key1", value) == 0) { printf("value1: %s\n", value); } // 写入ini文件 if (writeIniFile("config.ini", "section2", "key2", "value2") == 0) { printf("成功写入ini文件\n"); } return 0; } ``` 以上源码中的readIniFile函数用于读取指定section和key对应的value,writeIniFile函数用于向ini文件中写入新的section和key/value对。 使用main函数作为示例,打开名为"config.ini"的ini文件,并读取名为"section1"的section中的"key1"对应的value,并打印出来。然后向ini文件中写入一个名为"section2"的section,其中包含一个名为"key2"的key和"value2"的value。

相关推荐

最新推荐

recommend-type

linux系统中c++写日志文件功能分享

主要介绍了linux系统中c++写日志文件功能,简化了glog,只保留了写日志文件的功能,只是改写了linux版本,需要的朋友可以参考下
recommend-type

基于C++实现读取指定路径文件

主要介绍了基于C++实现读取指定路径文件,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
recommend-type

C++采用openfilename打开文件对话框用法实例

主要介绍了C++采用openfilename打开文件对话框用法实例,是C++文件操作中非常实用的技巧,需要的朋友可以参考下
recommend-type

C++ 读取文件内容到指定类型的变量方法

今天小编就为大家分享一篇C++ 读取文件内容到指定类型的变量方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
recommend-type

c++实现合并文件以及拆分实例代码

主要介绍了c++实现合并文件以及拆分实例代码,小编觉得还是挺不错的,具有一定借鉴价值,需要的朋友可以参考下
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

解释minorization-maximization (MM) algorithm,并给出matlab代码编写的例子

Minorization-maximization (MM) algorithm是一种常用的优化算法,用于求解非凸问题或含有约束的优化问题。该算法的基本思想是通过构造一个凸下界函数来逼近原问题,然后通过求解凸下界函数的最优解来逼近原问题的最优解。具体步骤如下: 1. 初始化参数 $\theta_0$,设 $k=0$; 2. 构造一个凸下界函数 $Q(\theta|\theta_k)$,使其满足 $Q(\theta_k|\theta_k)=f(\theta_k)$; 3. 求解 $Q(\theta|\theta_k)$ 的最优值 $\theta_{k+1}=\arg\min_\theta Q(
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。