配置文件读写案例

题目: 

配置文件读写

cfg.h 

#pragma once

#ifdef __cplusplus
extern "C"
{
	//函数声明
	int ReadCfgFile(char *file, char *key, char *value, int *len);
	int WriteCfgFile(char *file, char *key, char *value, int len);

}
#endif // __cplusplus

cfg.c

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#define SIZE 1024*8

int trimSpace(char *inbuf, char *outbuf)
{
	if (inbuf == NULL || outbuf == NULL)
	{
		return -1;
	}

	char *p = inbuf;
	int begin = 0;
	int end = strlen(p) - 1;
	int n = 0;

	if (end < 0)
	{
		return -2;
	}

	//从左往右移动,如果当前字符为空,而且没有结束
	while (isspace(p[begin]) && p[begin] != 0)
	{
		begin++;
	}

	while (isspace(p[end]) && end > 0 )
	{
		end--;
	}

	if (end == 0)
	{
		return -2;
	}
	
	n = end - begin + 1;//非空元素个数

	strncpy(outbuf, p + begin, n);
	outbuf[n] = 0;

	return 0;
}

int ReadCfgFile(char *file, char *key, char *value, int *len)
{
	if (file == NULL || key == NULL || value == NULL || len == NULL)
	{
		return -1;
	}

	FILE *fp = NULL;
	int ret = 0;
	char lineBuf[1024] = { 0 };
	char *p = NULL;
	int flag = 0; //0表示没有找到

	//打开文件
	fp = fopen(file, "r+");
	if (fp == NULL)
	{
		ret = -2;
		goto End;
	}

	while (1) {
		//读取1行
		if (fgets(lineBuf, sizeof(lineBuf), fp) == NULL)
		{
			break;
		}

		//lineBuf == "k1 = abc"
		//找key
		p = strstr(lineBuf, key);
		if (p == NULL) //没有
		{
			continue; //跳出本次循环
		}

		//重新设置起点
		p = p + strlen(key);

		//找 "="
		p = strstr(p, "=");
		if (p == NULL) //没有
		{
			continue; //跳出本次循环
		}

		//重新设置起点
		p = p + strlen("=");

		//获取非空字符
		ret = trimSpace(p, value);
		if (ret == 0)//成功
		{
			*len = strlen(value);
			flag = 1;
			goto End;
		}
		else
		{
			goto End;
		}
	}

End:
	if (fp != NULL)
	{
		fclose(fp);
	}
	if (flag == 0)
	{
		ret = -3;
		printf("没有%s对应的value\n", key);
	}

	return ret;
}

int WriteCfgFile(char *file, char *key, char *value, int len)
{
	if (file == NULL || key == NULL || value == NULL || len == NULL)
	{
		return -1;
	}

	FILE *fp = NULL;
	int ret = 0;
	char lineBuf[1024] = { 0 };
	char buf[SIZE] = { 0 };
	char *p = NULL;
	int flag = 0; //0表示没有找到

	fp = fopen(file, "r+");
	if (fp == NULL) //打开失败,有可能是配置文件没有创建
	{
		//创建配置文件
		fp = fopen(file, "w+");
		if (fp == NULL)
		{
			ret = -2;
			goto End;
		}
	}

	//获取文件大小
	//光标移动到结尾
	fseek(fp, 0, SEEK_END);

	long size = ftell(fp);
	if (size >= SIZE)
	{
		ret = -3;
		printf("文件大小超过8k,不支持");
		goto End;
	}

	//光标回到文件开头
	rewind(fp);

	while (1)
	{
		if (fgets(lineBuf, sizeof(lineBuf), fp) == NULL)
		{
			break;
		}

		//每一行是否包含key
		if (strstr(lineBuf, key) != NULL)
		{
			flag = 1;  //代表文件中已经有key值
			sprintf(lineBuf, "%s = %s\n", key, value);
			strcat(buf, lineBuf);
		}
		else
		{
			strcat(buf, lineBuf);
		}
	}

	//程序到这,2种情况
	if (0 == flag)  //没有key
	{
		//文件光标已经移动到文件结尾
		fprintf(fp, "%s = %s\n", key, value);
	}
	else //有key
	{
		//关闭文件
		if (fp != NULL)
		{
			fclose(fp);
			fp = NULL;
		}
		fp = fopen(file, "w+");
		if (fp == NULL)
		{
			ret = -4;
			goto End;
		}
		//重新写内容
		fputs(buf, fp);
	}

End:
	if (fp != NULL)
	{
		fclose(fp);
	}

	return ret;
}

main.c

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cfg.h"

#define CFGNAME "mycfg.ini"

void menu()
{
	printf("==========================\n");
	printf("1、读配置文件\n");
	printf("2、写配置文件\n");
	printf("3、清屏\n");
	printf("4、退出\n");
	printf("==========================\n");
}

void MyRead()
{
	char key[256] = { 0 };
	char value[1024] = { 0 };
	int len = 0;
	int ret = 0;

	printf("请输入key值:");
	scanf("%s", key);

	ret = ReadCfgFile(CFGNAME, key, value, &len);
	if (ret != 0)
	{
		printf("ReadCfgFile err:%d\n", ret);
		return;
	}

	printf("\n%s对应的value:%s, len = %d\n", key, value, len);
}

void MyWrite()
{
	char key[256] = { 0 };
	char value[1024] = { 0 };
	int len = 0;
	int ret = 0;

	printf("请输入key值:");
	scanf("%s", key);

	printf("请输入value值:");
	scanf("%s", value);

	ret = WriteCfgFile(CFGNAME, key, value, strlen(value));
	if (ret != 0)
	{
		printf("WriteCfgFile err:%d\n", ret);
		return;
	}

	printf("\n写入成功,输入的是:%s对应的value:%s, len = %d\n", key, value, strlen(value));

}

int main(void)
{
	int cmd;
	while (1)
	{
		menu();
		printf("cmd:");
		scanf("%d", &cmd);

		switch (cmd)
		{
		case 1:
			MyRead();
			break;
		case 2:
			MyWrite();
			break;
		case 3:
			system("cls");
			break;
		default:
			exit(0);
			break;
		}
	}

	printf("\n");
	system("pause");
	return 0;
}

 

以下是一个简单的实例,演示如何使用 C 语言读写 Linux 下的配置文件。 假设我们有一个名为 "config.ini" 的配置文件,内容如下: ``` [database] host = localhost username = root password = password123 port = 3306 [server] ip = 127.0.0.1 port = 8080 ``` 我们要使用 C 语言读取这个配置文件,并将其中的值存储在内存中,以便我们在程序中使用。 首先,我们需要定义一个结构体来存储配置文件中的值: ```c typedef struct { char database_host[100]; char database_username[100]; char database_password[100]; int database_port; char server_ip[100]; int server_port; } Config; ``` 接下来,我们需要编写函数来读取配置文件。以下是一个示例函数: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> void read_config_file(Config* config) { FILE* fp; char line[100]; char section[100]; char key[100]; char value[100]; fp = fopen("config.ini", "r"); if (fp == NULL) { printf("Error: could not open config file.\n"); exit(1); } while (fgets(line, sizeof(line), fp)) { // remove newline character line[strcspn(line, "\n")] = 0; if (line[0] == '[') { // new section strcpy(section, line); } else { // key-value pair sscanf(line, "%[^=]=%s", key, value); if (strcmp(section, "[database]") == 0) { if (strcmp(key, "host") == 0) { strcpy(config->database_host, value); } else if (strcmp(key, "username") == 0) { strcpy(config->database_username, value); } else if (strcmp(key, "password") == 0) { strcpy(config->database_password, value); } else if (strcmp(key, "port") == 0) { config->database_port = atoi(value); } } else if (strcmp(section, "[server]") == 0) { if (strcmp(key, "ip") == 0) { strcpy(config->server_ip, value); } else if (strcmp(key, "port") == 0) { config->server_port = atoi(value); } } } } fclose(fp); } ``` 该函数使用 fopen() 函数打开配置文件,并使用 fgets() 函数逐行读取文件内容。对于每一行,它检查行首是否为 "[",以确定当前行是否为一个新的配置部分。如果是,它将当前部分存储在 section 变量中。否则,它使用 sscanf() 函数从当前行中提取键值对,并将其存储在相应的结构体成员中。 最后,我们可以使用以下代码将配置文件的值读入内存中: ```c int main() { Config config; read_config_file(&config); printf("database host: %s\n", config.database_host); printf("database username: %s\n", config.database_username); printf("database password: %s\n", config.database_password); printf("database port: %d\n", config.database_port); printf("server ip: %s\n", config.server_ip); printf("server port: %d\n", config.server_port); return 0; } ``` 该代码调用 read_config_file() 函数,并将 Config 结构体的指针传递给它。然后,它打印每个配置值的值,以确保它们已正确读入内存中。 这就是一个简单的 Linux C 配置文件读写实例。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值