1 /*=========================================================================
4 Module: $RCSfile: gdcmUtil.cxx,v $
6 Date: $Date: 2004/11/16 10:25:53 $
7 Version: $Revision: 1.65 $
9 Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
10 l'Image). All rights reserved. See Doc/License.txt or
11 http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html for details.
13 This software is distributed WITHOUT ANY WARRANTY; without even
14 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 PURPOSE. See the above copyright notices for more information.
17 =========================================================================*/
20 #include "gdcmDebug.h"
22 // For GetCurrentDate, GetCurrentTime
24 #include <sys/types.h>
27 #include <stdarg.h> //only included in implementation file
28 #include <stdio.h> //only included in implementation file
30 #include <unistd.h> // for gethostname
31 #include <netdb.h> // for gethostbyname
38 * \brief Provide a better 'c++' approach for sprintf
39 * For example c code is:
40 * sprintf(trash, "%04x|%04x", group , element);
43 * std::ostringstream buf;
44 * buf << std::right << std::setw(4) << std::setfill('0') << std::hex
45 * << group << "|" << std::right << std::setw(4) << std::setfill('0')
46 * << std::hex << element;
50 std::string Util::Format(const char* format, ...)
54 va_start(args, format);
55 vsprintf(buffer, format, args); //might be a security flaw
56 va_end(args); // Each invocation of va_start should be matched
57 // by a corresponding invocation of va_end
58 // args is then 'undefined'
65 * \brief Because not available in C++ (?)
67 void Util::Tokenize (const std::string& str,
68 std::vector<std::string>& tokens,
69 const std::string& delimiters)
71 std::string::size_type lastPos = str.find_first_not_of(delimiters,0);
72 std::string::size_type pos = str.find_first_of (delimiters,lastPos);
73 while (std::string::npos != pos || std::string::npos != lastPos)
75 tokens.push_back(str.substr(lastPos, pos - lastPos));
76 lastPos = str.find_first_not_of(delimiters, pos);
77 pos = str.find_first_of (delimiters, lastPos);
83 * \brief Because not available in C++ (?)
84 * Counts the number of occurences of a substring within a string
87 int Util::CountSubstring (const std::string& str,
88 const std::string& subStr)
90 int count = 0; // counts how many times it appears
91 unsigned int x = 0; // The index position in the string
95 x = str.find(subStr,x); // Find the substring
96 if (x != std::string::npos) // If present
98 count++; // increase the count
99 x += subStr.length(); // Skip this word
102 while (x != std::string::npos); // Carry on until not present
109 * \brief Weed out a string from the non-printable characters (in order
110 * to avoid corrupting the terminal of invocation when printing)
111 * @param s string to remove non printable characters from
113 std::string Util::CreateCleanString(std::string const & s)
117 for(unsigned int i=0;i<str.size();i++)
127 if(!isprint(s[str.size()-1]))
129 if(s[str.size()-1]==0)
131 str[str.size()-1]=' ';
141 * \brief Add a SEPARATOR to the end of the name is necessary
142 * @param pathname file/directory name to normalize
144 std::string Util::NormalizePath(std::string const & pathname)
146 const char SEPARATOR_X = '/';
147 const char SEPARATOR_WIN = '\\';
148 const std::string SEPARATOR = "/";
149 std::string name = pathname;
150 int size = name.size();
152 if( name[size-1] != SEPARATOR_X && name[size-1] != SEPARATOR_WIN )
161 * \brief Get the (directory) path from a full path file name
162 * @param fullName file/directory name to extract Path from
164 std::string Util::GetPath(std::string const & fullName)
166 std::string res = fullName;
167 int pos1 = res.rfind("/");
168 int pos2 = res.rfind("\\");
183 * \brief Get the (last) name of a full path file name
184 * @param fullName file/directory name to extract end name from
186 std::string Util::GetName(std::string const & fullName)
188 std::string filename = fullName;
190 std::string::size_type slash_pos = filename.rfind("/");
191 std::string::size_type backslash_pos = filename.rfind("\\");
192 slash_pos = slash_pos > backslash_pos ? slash_pos : backslash_pos;
193 if(slash_pos != std::string::npos)
195 return filename.substr(slash_pos + 1);
205 * \brief Get the current date of the system in a dicom string
207 std::string Util::GetCurrentDate()
212 strftime(tmp,512,"%Y%m%d", localtime(&tloc) );
218 * \brief Get the current time of the system in a dicom string
220 std::string Util::GetCurrentTime()
225 strftime(tmp,512,"%H%M%S", localtime(&tloc) );
230 * \brief Create a /DICOM/ string:
231 * It should a of even length (no odd length ever)
232 * It can contain as many (if you are reading this from your
233 * editor the following character is is backslash followed by zero
234 * that needed to be escaped with an extra backslash for doxygen) \\0
237 std::string Util::DicomString(const char* s, size_t l)
239 std::string r(s, s+l);
240 assert( !(r.size() % 2) ); // == basically 'l' is even
246 * \brief Create a /DICOM/ string:
247 * It should a of even lenght (no odd length ever)
248 * It can contain as many (if you are reading this from your
249 * editor the following character is is backslash followed by zero
250 * that needed to be escaped with an extra backslash for doxygen) \\0
252 * This function is similar to DicomString(const char*),
253 * except it doesn't take a lenght.
254 * It only pad with a null character if length is odd
256 std::string Util::DicomString(const char* s)
258 size_t l = strlen(s);
263 std::string r(s, s+l);
264 assert( !(r.size() % 2) );
270 * \brief Safely compare two Dicom String:
271 * - Both string should be of even lenght
272 * - We allow padding of even lenght string by either a null
273 * character of a space
275 bool Util::DicomStringEqual(const std::string& s1, const char *s2)
277 // s2 is the string from the DICOM reference: 'MONOCHROME1'
278 std::string s1_even = s1; //Never change input parameter
279 std::string s2_even = DicomString( s2 );
280 if( s1_even[s1_even.size()-1] == ' ')
282 s1_even[s1_even.size()-1] = '\0'; //replace space character by null
284 return s1_even == s2_even;
289 * \brief Return the IP adress of the machine writting the DICOM image
291 std::string Util::GetIPAddress()
293 // This is a rip from http://www.codeguru.com/Cpp/I-N/internet/network/article.php/c3445/
294 #ifndef HOST_NAME_MAX
295 // SUSv2 guarantees that `Host names are limited to 255 bytes'.
296 // POSIX 1003.1-2001 guarantees that `Host names (not including the
297 // terminating NUL) are limited to HOST_NAME_MAX bytes'.
298 # define HOST_NAME_MAX 255
299 // In this case we should maybe check the string was not truncated.
300 // But I don't known how to check that...
301 #endif //HOST_NAME_MAX
304 char szHostName[HOST_NAME_MAX+1];
305 int r = gethostname(szHostName, HOST_NAME_MAX);
310 struct hostent * pHost = gethostbyname(szHostName);
312 for( int i = 0; pHost!= NULL && pHost->h_addr_list[i]!= NULL; i++ )
314 for( int j = 0; j<pHost->h_length; j++ )
316 if( j > 0 ) str += ".";
318 str += Util::Format("%u",
319 (unsigned int)((unsigned char*)pHost->h_addr_list[i])[j]);
321 // str now contains one local IP address
324 // If an error occur r == -1
325 // Most of the time it will return 127.0.0.1...
331 * \brief Creates a new UID. As stipulate in the DICOM ref
332 * each time a DICOM image is create it should have
333 * a unique identifier (URI)
335 std::string Util::CreateUniqueUID(const std::string& root)
337 // The code works as follow:
338 // echo "gdcm" | od -b
339 // 0000000 147 144 143 155 012
340 // Therefore we return
341 // radical + 147.144.143.155 + IP + time()
342 std::string radical = root;
343 if( !root.size() ) //anything better ?
345 radical = "0.0."; // Is this really usefull ?
348 // A root was specified use it to forge our new UID:
349 radical += "147.144.143.155"; // gdcm
351 radical += Util::GetIPAddress();
353 radical += Util::GetCurrentDate();
355 radical += Util::GetCurrentTime();
361 std::ostream& binary_write(std::ostream& os, const T& val)
363 return os.write(reinterpret_cast<const char*>(&val), sizeof val);
366 std::ostream& binary_write(std::ostream& os, const uint16_t& val)
368 #ifdef GDCM_WORDS_BIGENDIAN
370 swap = ((( val << 8 ) & 0x0ff00 ) | (( val >> 8 ) & 0x00ff ) );
371 return os.write(reinterpret_cast<const char*>(&swap), 2);
373 return os.write(reinterpret_cast<const char*>(&val), 2);
374 #endif //GDCM_WORDS_BIGENDIAN
377 std::ostream& binary_write(std::ostream& os, const uint32_t& val)
379 #ifdef GDCM_WORDS_BIGENDIAN
381 swap = ( ((val<<24) & 0xff000000) | ((val<<8) & 0x00ff0000) |
382 ((val>>8) & 0x0000ff00) | ((val>>24) & 0x000000ff) );
383 return os.write(reinterpret_cast<const char*>(&swap), 4);
385 return os.write(reinterpret_cast<const char*>(&val), 4);
386 #endif //GDCM_WORDS_BIGENDIAN
389 std::ostream& binary_write(std::ostream& os, const char* val)
391 return os.write(val, strlen(val));
394 std::ostream& binary_write(std::ostream& os, std::string const & val)
396 return os.write(val.c_str(), val.size());
399 } // end namespace gdcm