Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033 #include "cmtkResourceFile.h"
00034
00035 #include <string.h>
00036 #include <limits.h>
00037 #include <fstream>
00038 #include <algorithm>
00039
00040 #include <System/cmtkConsole.h>
00041
00042 namespace
00043 cmtk
00044 {
00045
00048
00049 void
00050 ResourceFile::Read( const char* fileName )
00051 {
00052 std::ifstream stream( fileName );
00053 if ( ! stream )
00054 {
00055 StdErr.printf( "Could not open resource file %s for reading.", fileName );
00056 return;
00057 }
00058
00059 char line[PATH_MAX];
00060 std::string section = "";
00061
00062 while ( !stream.eof() )
00063 {
00064 stream.getline( line, PATH_MAX );
00065
00066 if ( ! line[0] ) continue;
00067
00068 char* lastNonWS = line + strlen( line ) - 1;
00069 while ( (line <= lastNonWS) && isspace( *lastNonWS ) )
00070 --lastNonWS;
00071 *(lastNonWS+1) = 0;
00072
00073 if ( (line[0] == '[') && (*lastNonWS == ']') )
00074 {
00075 *lastNonWS = 0;
00076 section = line+1;
00077 }
00078 else
00079 {
00080 if ( section.length() )
00081 {
00082 (*this)[section].push_back( line );
00083 }
00084 }
00085
00086 line[0] = 0;
00087 }
00088 }
00089
00090 void
00091 ResourceFile::Write( const char* fileName ) const
00092 {
00093 std::ofstream stream( fileName );
00094 if ( ! stream )
00095 {
00096 StdErr.printf( "Could not open resource file %s for writing.", fileName );
00097 return;
00098 }
00099
00100 const_iterator sectionIt = this->begin();
00101 while ( sectionIt != this->end() )
00102 {
00103 stream << "[" << sectionIt->first << "]\n";
00104
00105 ResourceSection::const_iterator strIt = sectionIt->second.begin();
00106 while ( strIt != sectionIt->second.end() )
00107 {
00108 stream << *strIt << "\n";
00109 ++strIt;
00110 }
00111
00112 ++sectionIt;
00113 }
00114 }
00115
00116 unsigned int
00117 ResourceFile::AddUnique( const char* section, const char* entry, const unsigned int maxItems )
00118 {
00119 ResourceSection& sec = (*this)[section];
00120
00121
00122 ResourceSection::iterator it;
00123 while ( (it = std::find( sec.begin(), sec.end(), entry )) != sec.end() )
00124 {
00125 sec.erase( it );
00126 }
00127
00128
00129 sec.push_front( entry );
00130
00131
00132 if ( maxItems )
00133 {
00134 if ( sec.size() > maxItems )
00135 {
00136 ResourceSection::iterator it = sec.begin();
00137 for ( unsigned int i = 0; i < maxItems; ++i ) ++it;
00138 sec.erase( it, sec.end() );
00139 }
00140 }
00141 return sec.size();
00142 }
00143
00144 }