// Load // Attempts to load in the text file. If successful it will populate the // Section list with the key/value pairs found in the file. Note that comments // are saved so that they can be rewritten to the file later. bool CDataFile::Load(t_Str szFileName) { // We dont want to create a new file here. If it doesn't exist, just // return false and report the failure. std::fstream File(szFileName.c_str(), std::ios_base::in); // |std::ios_base::nocreate if ( File.is_open() ) { bool bDone = false; bool bAutoKey = (m_Flags & AUTOCREATE_KEYS) == AUTOCREATE_KEYS; bool bAutoSec = (m_Flags & AUTOCREATE_SECTIONS) == AUTOCREATE_SECTIONS; t_Str szLine; t_Str szComment; char buffer[MAX_BUFFER_LEN]; t_Section* pSection = GetSection(""); // These need to be set, we'll restore the original values later. m_Flags |= AUTOCREATE_KEYS; m_Flags |= AUTOCREATE_SECTIONS; while ( !bDone ) { memset(buffer, 0, MAX_BUFFER_LEN); File.getline(buffer, MAX_BUFFER_LEN); szLine = buffer; Trim(szLine); bDone = ( File.eof() || File.bad() || File.fail() ); if ( szLine.find_first_of(CommentIndicators) == 0 ) { szComment += "\n"; szComment += szLine; } else if ( szLine.find_first_of('[') == 0 ) // new section { szLine.erase( 0, 1 ); szLine.erase( szLine.find_last_of(']'), 1 ); CreateSection(szLine, szComment); pSection = GetSection(szLine); szComment = t_Str(""); } else if ( szLine.size() > 0 ) // we have a key, add this key/value pair { t_Str szKey = GetNextWord(szLine); t_Str szValue = szLine; if ( szKey.size() > 0 && szValue.size() > 0 ) { SetValue(szKey, szValue, szComment, pSection->szName); szComment = t_Str(""); } } } // Restore the original flag values. if ( !bAutoKey ) m_Flags &= ~AUTOCREATE_KEYS; if ( !bAutoSec ) m_Flags &= ~AUTOCREATE_SECTIONS; } else { Report(E_INFO, "[CDataFile::Load] Unable to open file. Does it exist?"); return false; } File.close(); return true; }
// GetValue // Returns the key value as a t_Str object. A return value of // t_Str("") indicates that the key could not be found. t_Str CDataFile::GetValue(t_Str szKey, t_Str szSection) { t_Key* pKey = GetKey(szKey, szSection); return (pKey == NULL) ? t_Str("") : pKey->szValue; }
// Clear // Resets the member variables to their defaults void CDataFile::Clear() { m_bDirty = false; m_szFileName = t_Str(""); m_Sections.clear(); }