C/C++编程:windows C/C++ 实现ini文件读写

1059 篇文章 280 订阅

ini格式稍微来说比较简单为:
[Tiatle]
字段1=内容
字段2=内容

内容为纯数字时,可以使用整形(int)方式读取,如果是字符串则需使用字符串(string)读取,部分代码需要用到Windows API 所以需加上windows.h头文件

使用多字节编码代码如下

1、获取程序路径

//获取程序路径
char* GetAppPath(char *AppPath,int nSize)
{
	int i;
	memset(AppPath,0,nSize);
#ifdef UNICODE
	GetModuleFileNameA(NULL,AppPath,nSize);
#else
	GetModuleFileName(NULL,AppPath,nSize);
#endif
	for (i = strlen(AppPath) + 1; i >= 0; i --)
	{
		if (AppPath[i] == '\\')
		{
			break;
		}
	}
	AppPath[i] = 0;
	return AppPath;
}

2、读取和写入ini配置文件

#include <iostream>
#include <windows.h>

int main()
{
	char app[1024] = {0};
	GetAppPath(app,sizeof(app));
	char filepath[1024] = {0};
	sprintf_s(filepath,"%s\\ConfigDevice.ini",app);

	char buf[1024] = "";
	char szTitle[] = "Title";
		//读取整形数据
#ifdef UNICODE
		int Number = GetPrivateProfileIntA(szTitle,"DeviceIndex",0,filepath);
		//读取字符串数据
		GetPrivateProfileStringA(szTitle,"DeviceName","TestData",buf,sizeof(buf),filepath);
#else
		int Number = GetPrivateProfileInt(szTitle,"DeviceIndex",0,filepath);
		GetPrivateProfileString(szTitle,"DeviceName","TestData",buf,sizeof(buf),filepath);
#endif


		//写入整形数据
		char szTmp[64];
		sprintf(szTmp,"%d",Number);
#ifdef UNICODE
		WritePrivateProfileStringA(szTitle,"DeviceIndex",szTmp,filepath);
		//直接写入字符串数据
		WritePrivateProfileStringA(szTitle,"DeviceName","WriteData2",filepath);
#else
		WritePrivateProfileString(szTitle,"DeviceIndex",szTmp,filepath);
		WritePrivateProfileString(szTitle,"DeviceName","WriteData",filepath);
#endif
}

程序运行结果:
在运行目录下生成ConfigDevice.ini文件,内容是程序写入的
在这里插入图片描述

使用Unicode字符编码

#include <iostream>
#include <windows.h>


LPWSTR toUnicode(const char* _str)
{
	LPWSTR _ret;
	int _len = strlen(_str) * 2;

	_ret = new WCHAR[_len];

	MultiByteToWideChar(CP_ACP, 0, _str, -1, _ret, _len);

	return _ret;
}

//获取程序路径
wchar_t* GetAppPath(wchar_t *AppPath,int nSize)
{
	int i;
	memset(AppPath,0,nSize);
	GetModuleFileName(NULL,AppPath,nSize);
	for (i = wcslen(AppPath) + 1; i >= 0; i --)
	{
		if (AppPath[i] == '\\')
		{
			break;
		}
	}
	AppPath[i] = 0;
	return AppPath;
}

int main()
{
	wchar_t app[1024] = {0};
	GetAppPath(app,sizeof(app));
	wchar_t filepath[512] = {0};
	wsprintf(filepath,toUnicode("%s\\ConfigDevice.ini"),app);

	wchar_t buf[2048] = {0};
	wchar_t szTitle[10] = {0};
	//memcpy(szTitle,toUnicode("Title"),sizeof("Title"));
	wcsncpy_s(szTitle,toUnicode("Title"),sizeof("Title"));
	//读取整形数据
	int Number = GetPrivateProfileInt(szTitle,toUnicode("DeviceIndex"),0,filepath);
	//读取字符串数据
	GetPrivateProfileString(szTitle,toUnicode("DeviceName"),toUnicode(""),buf,sizeof(buf),filepath);

	//写入整形数据
	char szTmp[64];
	sprintf(szTmp,"%d",Number);
	WritePrivateProfileString(szTitle,toUnicode("DeviceIndex"),toUnicode(szTmp),filepath);
	//直接写入字符串数据
	WritePrivateProfileString(szTitle,toUnicode("DeviceName"),toUnicode("WriteData"),filepath);

	wprintf(toUnicode("%s\n"),buf);
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
纯c读写ini配置文件 用c/c++读写ini配置文件有不少第三方的开源库,如iniparser、libini、rwini、UltraLightINIParser等,但都不理想,往往代码较大、功能较弱、 接口使用不方便。尤其在大小写处理、前后空格、各种注释、跨平台换行符支持、带引号字符串处理、无section操作、原格式保持等方面存在问题。 现将本人精心制作的ini读写程序源码奉献给大家,纯c编写,简洁好用。支持windows和linux。 主要特点: 1、支持;和#注释符号,支持行尾注释。 2、支持带引号'或"成对匹配的字符串,提取时自动去引号。引号中可带其它引号或;#注释符。 3、支持无section或空section(名称为空)。 4、支持10、16、8进制数,0x开头为16进制数,0开头为8进制。 5、支持section、key或=号前后带空格。 6、支持\n、\r、\r\n或\n\r换行格式。 7、不区分section、key大小写,但写入时以新串为准,并保持其大小写。 8、新增数据时,若section存在则在该节最后一个有效数据后添加,否则在文件尾部添加。 9、支持指定key所在整行删除,即删除该键值,包括注释。 10、可自动跳过格式错误行,修改时仍然保留。 11、修改时保留原注释:包括整行注释、行尾注释(包括前面空格)。 12、修改时保留原空行。以上三点主要是尽量保留原格式。 不足之处: 1、不支持单key多value(逗号分割),只能一次性提取后自行处理。 2、不支持同名重复section和key。(重复section可视为错误,重复key则可能造成分歧) 3、不能提取所有section或key名称。 使用只需两个文件inirw.h、inirw.c,另有测试程序和工程文件,支持windows和linux。
### 回答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。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值