Advertisement
Guest User

Untitled

a guest
Mar 23rd, 2017
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. #ifndef _CONFIG_H_
  2. #define _CONFIG_H_
  3.  
  4. #include <fstream>
  5. #include <sstream>
  6. #include <vector>
  7.  
  8. class dConf
  9. {
  10. public:
  11. static std::string getValueByKey(std::string fname, std::string key)
  12. {
  13. std::ifstream in(fname.c_str());
  14. std::string s, f1, f2, f3;
  15.  
  16. s = "";
  17. while (std::getline(in, s)) {
  18. std::istringstream iss(s);
  19. if (iss >> f1 >> f2 >> f3 && f1 == key) {
  20. s = f3;
  21. break;
  22. }
  23. }
  24. in.close();
  25. return s;
  26. }
  27.  
  28. static void setValueByKey(std::string fname, std::string key, std::string newValue)
  29. {
  30. std::string f1, f2, f3;
  31. std::ifstream ifs(fname.c_str());
  32. std::vector<std::string> Vec;
  33. while (!ifs.eof()) { std::string s; std::getline(ifs, s); Vec.push_back(s); } //читаем файл в вектор строк
  34. for (std::vector<std::string>::iterator it = Vec.begin(); it != Vec.end(); ++it) { //меняем нужную строку
  35. std::istringstream iss(*it);
  36. if (iss >> f1 >> f2 >> f3 && f1 == key) {
  37. *it = f1 + " " + f2 + " " + newValue;
  38. break;
  39. }
  40. }
  41. ifs.close();
  42. std::ofstream ofs(fname.c_str());
  43. for (std::vector<std::string>::iterator it = Vec.begin(); it != Vec.end(); ++it) { //пишем вектор в файл
  44. if (*it == "") //во избежание пустых строк при перезаписи //костыль?
  45. continue;
  46. ofs << *it << std::endl;
  47. }
  48. ofs.close();
  49. }
  50.  
  51. //=================================someConvertors
  52. static inline bool stringToBool(std::string const& s)//convert string to bool
  53. {
  54. if (s == "0")
  55. return false;
  56. else
  57. return true;
  58. }
  59.  
  60. static inline const char * const boolToString(bool b)//convert bool to string
  61. {
  62. return b ? "1" : "0";
  63. }
  64.  
  65. }; //end namespace dConf
  66. #endif _CONFIG_H_
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement