Advertisement
pycache

norbi

Jul 29th, 2018
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.70 KB | None | 0 0
  1. #include <string>
  2. #include <iostream>
  3. #include <fstream>
  4. #include <windows.h>
  5. #include <vector>
  6. #include <iomanip>
  7. #include <sstream>
  8. #include <set>
  9.  
  10. class CIniWriter {
  11. private:
  12.     void AppendNewline(std::string szSection) {
  13.         if (!m_vecUsedCategories.empty())
  14.             if (m_vecUsedCategories.find(szSection) == m_vecUsedCategories.end()) {
  15.                 m_sFileStream.seekp(0, std::ios_base::end);
  16.                 m_sFileStream << "\n";
  17.                 m_sFileStream.seekp(0, std::ios_base::end);
  18.             }
  19.         m_vecUsedCategories.emplace(szSection);
  20.     }
  21.  
  22. public:
  23.     CIniWriter(std::string szFileName) {
  24.         m_szFileName = szFileName;
  25.         m_sFileStream = std::ofstream(szFileName);
  26.     }
  27.  
  28.     ~CIniWriter() {
  29.         m_sFileStream.close();
  30.     }
  31.  
  32.     template<typename T> void WriteValue(std::string szSection, std::string szKey, T tValue, bool hex = false) {
  33.         AppendNewline(szSection);
  34.         std::string val;
  35.         if constexpr (std::is_same_v<T, const char*> || std::is_same_v<T, std::string>)
  36.             val = tValue;
  37.         else if constexpr (std::is_same_v<T, int>) {
  38.             std::stringstream vss;
  39.             vss << (hex ? std::hex : std::dec) << (hex ? "0x" : "") << tValue;
  40.             val = vss.str();
  41.         else
  42.             val = std::to_string(tValue);
  43.         }
  44.         WritePrivateProfileString(szSection.c_str(), szKey.c_str(), val.c_str(), m_szFileName.c_str());
  45.     }
  46.  
  47. private:
  48.     std::string m_szFileName;
  49.     std::set<std::string> m_vecUsedCategories;
  50.     std::ofstream m_sFileStream;
  51. };
  52.  
  53. int main() {
  54.     CIniWriter writer("C:/Users/M/Desktop/test.ini");
  55.     writer.WriteValue("Category", "Bool1", true);
  56.     writer.WriteValue("Category", "Int1", 100);
  57.     writer.WriteValue("Category", "Int2", 100, true);
  58.     writer.WriteValue("Category2", "Bool1", false);
  59.     writer.WriteValue("Category2", "Str1", "roflcopter");
  60.     return 0;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement