1 /*=========================================================================
4 Module: $RCSfile: gdcmUtil.cxx,v $
6 Date: $Date: 2004/11/16 16:49:01 $
7 Version: $Revision: 1.67 $
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 #if defined _MSC_VER || defined(__BORLANDC__)
31 #include <winsock.h> // for gethostname & gethostbyname
34 #include <unistd.h> // for gethostname
35 #include <netdb.h> // for gethostbyname
42 * \brief Provide a better 'c++' approach for sprintf
43 * For example c code is:
44 * sprintf(trash, "%04x|%04x", group , element);
47 * std::ostringstream buf;
48 * buf << std::right << std::setw(4) << std::setfill('0') << std::hex
49 * << group << "|" << std::right << std::setw(4) << std::setfill('0')
50 * << std::hex << element;
54 std::string Util::Format(const char* format, ...)
58 va_start(args, format);
59 vsprintf(buffer, format, args); //might be a security flaw
60 va_end(args); // Each invocation of va_start should be matched
61 // by a corresponding invocation of va_end
62 // args is then 'undefined'
69 * \brief Because not available in C++ (?)
71 void Util::Tokenize (const std::string& str,
72 std::vector<std::string>& tokens,
73 const std::string& delimiters)
75 std::string::size_type lastPos = str.find_first_not_of(delimiters,0);
76 std::string::size_type pos = str.find_first_of (delimiters,lastPos);
77 while (std::string::npos != pos || std::string::npos != lastPos)
79 tokens.push_back(str.substr(lastPos, pos - lastPos));
80 lastPos = str.find_first_not_of(delimiters, pos);
81 pos = str.find_first_of (delimiters, lastPos);
87 * \brief Because not available in C++ (?)
88 * Counts the number of occurences of a substring within a string
91 int Util::CountSubstring (const std::string& str,
92 const std::string& subStr)
94 int count = 0; // counts how many times it appears
95 unsigned int x = 0; // The index position in the string
99 x = str.find(subStr,x); // Find the substring
100 if (x != std::string::npos) // If present
102 count++; // increase the count
103 x += subStr.length(); // Skip this word
106 while (x != std::string::npos); // Carry on until not present
113 * \brief Weed out a string from the non-printable characters (in order
114 * to avoid corrupting the terminal of invocation when printing)
115 * @param s string to remove non printable characters from
117 std::string Util::CreateCleanString(std::string const & s)
121 for(unsigned int i=0; i<str.size(); i++)
123 if(!isprint((unsigned char)str[i]))
131 if(!isprint((unsigned char)s[str.size()-1]))
133 if(s[str.size()-1] == 0)
135 str[str.size()-1] = ' ';
145 * \brief Add a SEPARATOR to the end of the name is necessary
146 * @param pathname file/directory name to normalize
148 std::string Util::NormalizePath(std::string const & pathname)
150 const char SEPARATOR_X = '/';
151 const char SEPARATOR_WIN = '\\';
152 const std::string SEPARATOR = "/";
153 std::string name = pathname;
154 int size = name.size();
156 if( name[size-1] != SEPARATOR_X && name[size-1] != SEPARATOR_WIN )
165 * \brief Get the (directory) path from a full path file name
166 * @param fullName file/directory name to extract Path from
168 std::string Util::GetPath(std::string const & fullName)
170 std::string res = fullName;
171 int pos1 = res.rfind("/");
172 int pos2 = res.rfind("\\");
187 * \brief Get the (last) name of a full path file name
188 * @param fullName file/directory name to extract end name from
190 std::string Util::GetName(std::string const & fullName)
192 std::string filename = fullName;
194 std::string::size_type slash_pos = filename.rfind("/");
195 std::string::size_type backslash_pos = filename.rfind("\\");
196 slash_pos = slash_pos > backslash_pos ? slash_pos : backslash_pos;
197 if(slash_pos != std::string::npos)
199 return filename.substr(slash_pos + 1);
209 * \brief Get the current date of the system in a dicom string
211 std::string Util::GetCurrentDate()
216 strftime(tmp,512,"%Y%m%d", localtime(&tloc) );
222 * \brief Get the current time of the system in a dicom string
224 std::string Util::GetCurrentTime()
229 strftime(tmp,512,"%H%M%S", localtime(&tloc) );
234 * \brief Create a /DICOM/ string:
235 * It should a of even length (no odd length ever)
236 * It can contain as many (if you are reading this from your
237 * editor the following character is is backslash followed by zero
238 * that needed to be escaped with an extra backslash for doxygen) \\0
241 std::string Util::DicomString(const char* s, size_t l)
243 std::string r(s, s+l);
244 assert( !(r.size() % 2) ); // == basically 'l' is even
250 * \brief Create a /DICOM/ string:
251 * It should a of even lenght (no odd length ever)
252 * It can contain as many (if you are reading this from your
253 * editor the following character is is backslash followed by zero
254 * that needed to be escaped with an extra backslash for doxygen) \\0
256 * This function is similar to DicomString(const char*),
257 * except it doesn't take a lenght.
258 * It only pad with a null character if length is odd
260 std::string Util::DicomString(const char* s)
262 size_t l = strlen(s);
267 std::string r(s, s+l);
268 assert( !(r.size() % 2) );
274 * \brief Safely compare two Dicom String:
275 * - Both string should be of even lenght
276 * - We allow padding of even lenght string by either a null
277 * character of a space
279 bool Util::DicomStringEqual(const std::string& s1, const char *s2)
281 // s2 is the string from the DICOM reference: 'MONOCHROME1'
282 std::string s1_even = s1; //Never change input parameter
283 std::string s2_even = DicomString( s2 );
284 if( s1_even[s1_even.size()-1] == ' ')
286 s1_even[s1_even.size()-1] = '\0'; //replace space character by null
288 return s1_even == s2_even;
293 * \brief Return the IP adress of the machine writting the DICOM image
295 std::string Util::GetIPAddress()
297 // This is a rip from http://www.codeguru.com/Cpp/I-N/internet/network/article.php/c3445/
298 #ifndef HOST_NAME_MAX
299 // SUSv2 guarantees that `Host names are limited to 255 bytes'.
300 // POSIX 1003.1-2001 guarantees that `Host names (not including the
301 // terminating NUL) are limited to HOST_NAME_MAX bytes'.
302 # define HOST_NAME_MAX 255
303 // In this case we should maybe check the string was not truncated.
304 // But I don't known how to check that...
305 #endif //HOST_NAME_MAX
308 char szHostName[HOST_NAME_MAX+1];
309 int r = gethostname(szHostName, HOST_NAME_MAX);
314 struct hostent * pHost = gethostbyname(szHostName);
316 for( int i = 0; pHost!= NULL && pHost->h_addr_list[i]!= NULL; i++ )
318 for( int j = 0; j<pHost->h_length; j++ )
320 if( j > 0 ) str += ".";
322 str += Util::Format("%u",
323 (unsigned int)((unsigned char*)pHost->h_addr_list[i])[j]);
325 // str now contains one local IP address
328 // If an error occur r == -1
329 // Most of the time it will return 127.0.0.1...
335 * \brief Creates a new UID. As stipulate in the DICOM ref
336 * each time a DICOM image is create it should have
337 * a unique identifier (URI)
339 std::string Util::CreateUniqueUID(const std::string& root)
341 // The code works as follow:
342 // echo "gdcm" | od -b
343 // 0000000 147 144 143 155 012
344 // Therefore we return
345 // radical + 147.144.143.155 + IP + time()
346 std::string radical = root;
347 if( !root.size() ) //anything better ?
349 radical = "0.0."; // Is this really usefull ?
352 // A root was specified use it to forge our new UID:
353 radical += "147.144.143.155"; // gdcm
355 radical += Util::GetIPAddress();
357 radical += Util::GetCurrentDate();
359 radical += Util::GetCurrentTime();
365 std::ostream& binary_write(std::ostream& os, const T& val)
367 return os.write(reinterpret_cast<const char*>(&val), sizeof val);
370 std::ostream& binary_write(std::ostream& os, const uint16_t& val)
372 #ifdef GDCM_WORDS_BIGENDIAN
374 swap = ((( val << 8 ) & 0x0ff00 ) | (( val >> 8 ) & 0x00ff ) );
375 return os.write(reinterpret_cast<const char*>(&swap), 2);
377 return os.write(reinterpret_cast<const char*>(&val), 2);
378 #endif //GDCM_WORDS_BIGENDIAN
381 std::ostream& binary_write(std::ostream& os, const uint32_t& val)
383 #ifdef GDCM_WORDS_BIGENDIAN
385 swap = ( ((val<<24) & 0xff000000) | ((val<<8) & 0x00ff0000) |
386 ((val>>8) & 0x0000ff00) | ((val>>24) & 0x000000ff) );
387 return os.write(reinterpret_cast<const char*>(&swap), 4);
389 return os.write(reinterpret_cast<const char*>(&val), 4);
390 #endif //GDCM_WORDS_BIGENDIAN
393 std::ostream& binary_write(std::ostream& os, const char* val)
395 return os.write(val, strlen(val));
398 std::ostream& binary_write(std::ostream& os, std::string const & val)
400 return os.write(val.c_str(), val.size());
403 } // end namespace gdcm