2020-08-30

#include<vector>
#include <string>
#include <iostream>
#include <unordered_map>
#include <map>
#include <fstream>
using namespace std;
typedef unsigned int Uint32;
Uint32 string_to_unsigned_int(string str) {
    Uint32 result(0);
    for (int i = str.size() - 1; i >= 0; i--) {
        Uint32 temp = 0;
        Uint32 k = str.size() - i - 1;
        if (isdigit(str[i])) {
            temp = str[i] - '0';
            while (k--) temp *= 10;
            result += temp;
        }
        else break;
    }
    if (str[0] == '-') return (Uint32)(-result);
    return result;
}

void creat_hash_table(const char*fileName, unordered_map<string, Uint32> &res, Uint32 *Err, Uint32 PrintFlag) {
    printf("read %s\n", fileName);
    char fileName_s[200];
    strcpy(fileName_s, fileName);
    ifstream ifs;
    ifs.open(fileName_s, ios::in);
    if (!ifs.is_open()) {
        cout << "failed to open File:" << endl;
        return;
    }
    string tmp;
    while (getline(ifs, tmp)) {
        int position = tmp.find("=");
        int position2 = tmp.find(";");
        if (position != tmp.npos && position2 != tmp.npos) {
            string temp = tmp.substr(0, position);
            int len = position2 - position - 1;
            string vaule_s = temp.substr(position + 1, len);
            Uint32 vaule = string_to_unsigned_int(vaule_s);
            res.insert(make_pair(temp, vaule));
        }
        else continue;
    }
    return;
}

class singletonFile {
private:
    static singletonFile *local_instance;
    singletonFile() {};
public:
    unordered_map<string, unordered_map<string, Uint32>> res;
    static singletonFile *getInstance() {
        if (local_instance == nullptr) {
            local_instance = new singletonFile();
        }
        return local_instance;
    }
    Uint32 getval(const char* fileName, const char*valName, Uint32 *Err, Uint32 PrintFlag) {
        Uint32 Errcode;
        string fileName2 = fileName;
        if (res.find(fileName2) == res.end()) {
            unordered_map<string, Uint32> temp;
            creat_hash_table(fileName, temp, Err, PrintFlag);
            if (temp.size() != 0) res[fileName2] = temp;
            else {
                *Err = 1;
                return 0;
            }
        }
        string tmp = valName;
        if (res[fileName2].find(tmp) != res[fileName2].end()) {
            *Err = 0;
            return res[fileName][tmp];
        }
        else {
            *Err = 2;
            if (PrintFlag) cout << "cannot find para as: " << valName << endl;
            return 0;
        }
    }
};

Uint32 get_Uint32(const char*filename, const char* valname, Uint32*flag, Uint32 Printflag) {
    singletonFile* s = singletonFile::getInstance();
    Uint32 result = s->getval(filename, valname, flag, Printflag);
    return result;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。