过滤出属性值对

#include <iostream>
#include <fstream>
#include <vector>
#include <string.h>
#include <stdlib.h>

using namespace std;

typedef struct DataUnit DataUnit;

struct DataUnit {
	char* key;
	char* value;
	DataUnit* previous;
	DataUnit* next;
};

char* GetKey(char* p, char** begin, char** end) {
	char* a = p;

	for (; *a == ' '; a--) {
	}
	*end = a;
	a--;

	for (; *a != ' '; a--) {
	}
	*begin = ++a;

	return *begin;
}

char* GetValue(char* p, char** begin, char** end) {
	char* a = p;

	for (; *a != '\"'; a++) {
	}
	*begin = ++a;
	a++;

	for (; *a != '\"'; a++) {
	}
	*end = a;

	return *begin;
}

DataUnit* SplitString(const char* source_string, DataUnit* head) {
	DataUnit* one = head;

	char* str = const_cast<char*>(source_string);
	char* begin = NULL;
	char* end = NULL;
	char* p = NULL;

	do {
		p = strchr(str, '=');
		if (NULL == p) {
			return one;
		}

		DataUnit* unit = (DataUnit*) malloc(sizeof(DataUnit));
		memset(unit, 0, sizeof(DataUnit));

		GetKey(p, &begin, &end);
		unit->key = (char*) malloc(end - begin + 1);
		memset(unit->key, 0, end - begin + 1);
		strncpy(unit->key, begin, end - begin);

		GetValue(p, &begin, &end);
		unit->value = (char*) malloc(end - begin + 1);
		memset(unit->value, 0, end - begin + 1);
		strncpy(unit->value, begin, end - begin);

		unit->previous = one;
		one->next = unit;
		one = unit;

		str = end++;
	} while (p != NULL);

	return one;
}

int readConfigFile(string file_path) {
	ifstream input;
	input.open(file_path.c_str());
	if (!input.is_open()) {
		cout << "Open file: " << file_path << "fail~~" << endl;
		return -1;
	}

	DataUnit* head = (DataUnit*) malloc(sizeof(DataUnit));
	memset(head, 0, sizeof(DataUnit));
	DataUnit* node = head;

	string str;
	while (!input.eof()) {
		getline(input, str);
		node = SplitString(str.c_str(), node);
	}
	input.close();

	DataUnit one;
	one.next = head->next;
	for (; one.next != NULL; one = *(one.next)) {
		cout << one.next->key << "                " << one.next->value << endl;
	}

	return 0;
}

int main(int argc, char** argv) {
	if (argc != 2) {
		return -1;
	}

	string file_path = argv[1];

	readConfigFile(file_path);

	return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值