[C/C++]伪读写ini配置文件

实现读取下面文件,并获得每行内容(等号左侧为key,等号右侧为value)

scanfolder=E:\3D Objects
host=192.168.88.72
port=21
user=admin
pwd=123456
delay=300
fileext=zip

直接上代码

filez.h

#ifndef FTP_FILE_N
#define FTP_FILE_N
#include <string>
#include <map>
using std::map;
using std::string;

/* 获得filepath的内容,并保存map
   例子:
   std::map<char*, char*> map = get_key_value("./config.ini");
   std::cout << map.find("user")->second << std::endl;
*/
map<string, string> get_key_value(char* filepath);

#endif // !FTP_FILE_N

filez.cpp

//
//  filez.cpp
//  ftpz
//
//  Created by 胖胖的ALEX on 2017/10/25.
//
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <vector>
#include <map>
#include "stringz.h"
using std::map;
using std::string;

map<string, string> get_key_value(char* filepath)
{
	
	map<string, string> map;
	FILE *fp;
	char str[1024];

	fp = fopen(filepath, "r");
	if (fp == NULL) {
		std::cout << "打开文件时发生错误" << std::endl;
	}
	while (true)
	{
		if (feof(fp)) {
			break;
		}
		memset(str, 0, sizeof(str));
		if (fgets(str, 1024, fp) != NULL)
		{
			std::vector<char*> vec = split_z(str, "=");
			rtrim_n_z(vec[1]);
			typedef std::pair<string, string> p;
			p pro(vec[0], vec[1]);
			map.insert(pro);

			vec.clear();
		}
	}
	fclose(fp);

	return map;
}

使用方法

#define CONFIGFILE "./config.ini"
int main()
{
	// 0.读取配置文件
	std::map<string, string> map = get_key_value(CONFIGFILE);
	std::string fileext = map.find("fileext")->second;
	std::string scanfolder = map.find("scanfolder")->second;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值