Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <string>
- #include <iostream>
- #include <fstream>
- #include <windows.h>
- #include <vector>
- #include <iomanip>
- #include <sstream>
- #include <set>
- class CIniWriter {
- private:
- void AppendNewline(std::string szSection) {
- if (!m_vecUsedCategories.empty())
- if (m_vecUsedCategories.find(szSection) == m_vecUsedCategories.end()) {
- m_sFileStream.seekp(0, std::ios_base::end);
- m_sFileStream << "\n";
- m_sFileStream.seekp(0, std::ios_base::end);
- }
- m_vecUsedCategories.emplace(szSection);
- }
- public:
- CIniWriter(std::string szFileName) {
- m_szFileName = szFileName;
- m_sFileStream = std::ofstream(szFileName);
- }
- ~CIniWriter() {
- m_sFileStream.close();
- }
- template<typename T> void WriteValue(std::string szSection, std::string szKey, T tValue, bool hex = false) {
- AppendNewline(szSection);
- std::string val;
- if constexpr (std::is_same_v<T, const char*> || std::is_same_v<T, std::string>)
- val = tValue;
- else if constexpr (std::is_same_v<T, int>) {
- std::stringstream vss;
- vss << (hex ? std::hex : std::dec) << (hex ? "0x" : "") << tValue;
- val = vss.str();
- else
- val = std::to_string(tValue);
- }
- WritePrivateProfileString(szSection.c_str(), szKey.c_str(), val.c_str(), m_szFileName.c_str());
- }
- private:
- std::string m_szFileName;
- std::set<std::string> m_vecUsedCategories;
- std::ofstream m_sFileStream;
- };
- int main() {
- CIniWriter writer("C:/Users/M/Desktop/test.ini");
- writer.WriteValue("Category", "Bool1", true);
- writer.WriteValue("Category", "Int1", 100);
- writer.WriteValue("Category", "Int2", 100, true);
- writer.WriteValue("Category2", "Bool1", false);
- writer.WriteValue("Category2", "Str1", "roflcopter");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement