实现读取下面文件,并获得每行内容(等号左侧为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;
}