2323
2424// /////////////////////////////////////////////////////////////////////////////
2525//
26- // /mINI/ v0.9.12
26+ // /mINI/ v0.9.13
2727// An INI file reader and writer for the modern age.
2828//
2929// /////////////////////////////////////////////////////////////////////////////
@@ -332,19 +332,31 @@ namespace mINI
332332 using T_LineData = std::vector<std::string>;
333333 using T_LineDataPtr = std::shared_ptr<T_LineData>;
334334
335+ bool isBOM = false ;
336+
335337 private:
336338 std::ifstream fileReadStream;
337339 T_LineDataPtr lineData;
338340
339341 T_LineData readFile ()
340342 {
341- const char header[3 ] = {(char )fileReadStream.get (), (char )fileReadStream.get (), (char )fileReadStream.get ()};
342- const bool isBOM = header[0 ] == (char )0xEF && header[1 ] == (char )0xBB && header[2 ] == (char )0xBF ;
343- std::string fileContents;
344343 fileReadStream.seekg (0 , std::ios::end);
345- fileContents.resize (static_cast <std::size_t >(fileReadStream.tellg ()));
344+ const std::size_t fileSize = static_cast <std::size_t >(fileReadStream.tellg ());
345+ fileReadStream.seekg (0 , std::ios::beg);
346+ if (fileSize >= 3 ) {
347+ const char header[3 ] = {
348+ static_cast <char >(fileReadStream.get ()),
349+ static_cast <char >(fileReadStream.get ()),
350+ static_cast <char >(fileReadStream.get ())
351+ };
352+ isBOM = header[0 ] == (char )0xEF && header[1 ] == (char )0xBB && header[2 ] == (char )0xBF ;
353+ }
354+ else {
355+ isBOM = false ;
356+ }
357+ std::string fileContents;
358+ fileContents.resize (fileSize);
346359 fileReadStream.seekg (isBOM ? 3 : 0 , std::ios::beg);
347- std::size_t fileSize = fileContents.size ();
348360 fileReadStream.read (&fileContents[0 ], fileSize);
349361 fileReadStream.close ();
350362 T_LineData output;
@@ -678,11 +690,13 @@ namespace mINI
678690 INIStructure originalData;
679691 T_LineDataPtr lineData;
680692 bool readSuccess = false ;
693+ bool fileIsBOM = false ;
681694 {
682695 INIReader reader (filename, true );
683696 if ((readSuccess = reader >> originalData))
684697 {
685698 lineData = reader.getLines ();
699+ fileIsBOM = reader.isBOM ;
686700 }
687701 }
688702 if (!readSuccess)
@@ -693,6 +707,10 @@ namespace mINI
693707 std::ofstream fileWriteStream (filename, std::ios::out | std::ios::binary);
694708 if (fileWriteStream.is_open ())
695709 {
710+ if (fileIsBOM) {
711+ const char utf8_BOM[3 ] = {(char )0xEF , (char )0xBB , (char )0xBF };
712+ fileWriteStream.write (utf8_BOM, 3 );
713+ }
696714 if (output.size ())
697715 {
698716 auto line = output.begin ();
0 commit comments