1 /*=========================================================================
4 Module: $RCSfile: gdcmUtil.cxx,v $
6 Date: $Date: 2004/11/16 02:54:35 $
7 Version: $Revision: 1.64 $
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 name 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) );
231 * \brief Create a /DICOM/ string:
232 * It should a of even length (no odd length ever)
233 * It can contains as many \0 as you want.
235 std::string Util::DicomString(const char* s, size_t l)
237 std::string r(s, s+l);
238 assert( !(r.size() % 2) ); // == basically 'l' is even
244 * \brief Create a /DICOM/ string:
245 * It should a of even lenght (no odd length ever)
246 * It can contains as many \0 as you want.
247 * This function is similar to DicomString(const char*),
248 * except it doesn't take a lenght.
249 * It only pad with a null character if length is odd
251 std::string Util::DicomString(const char* s)
253 size_t l = strlen(s);
258 std::string r(s, s+l);
259 assert( !(r.size() % 2) );
265 * \brief Safely compare two Dicom String:
266 * - Both string should be of even lenght
267 * - We allow padding of even lenght string by either a null
268 * character of a space
270 bool Util::DicomStringEqual(const std::string& s1, const char *s2)
272 // s2 is the string from the DICOM reference: 'MONOCHROME1'
273 std::string s1_even = s1; //Never change input parameter
274 std::string s2_even = DicomString( s2 );
275 if( s1_even[s1_even.size()-1] == ' ')
277 s1_even[s1_even.size()-1] = '\0'; //replace space character by null
279 return s1_even == s2_even;
284 * \brief Return the IP adress of the machine writting the DICOM image
286 std::string Util::GetIPAddress()
288 // This is a rip from http://www.codeguru.com/Cpp/I-N/internet/network/article.php/c3445/
289 #ifndef HOST_NAME_MAX
290 // SUSv2 guarantees that `Host names are limited to 255 bytes'.
291 // POSIX 1003.1-2001 guarantees that `Host names (not including the
292 // terminating NUL) are limited to HOST_NAME_MAX bytes'.
293 # define HOST_NAME_MAX 255
294 // In this case we should maybe check the string was not truncated.
295 // But I don't known how to check that...
296 #endif //HOST_NAME_MAX
299 char szHostName[HOST_NAME_MAX+1];
300 int r = gethostname(szHostName, HOST_NAME_MAX);
305 struct hostent * pHost = gethostbyname(szHostName);
307 for( int i = 0; pHost!= NULL && pHost->h_addr_list[i]!= NULL; i++ )
309 for( int j = 0; j<pHost->h_length; j++ )
311 if( j > 0 ) str += ".";
313 str += Util::Format("%u",
314 (unsigned int)((unsigned char*)pHost->h_addr_list[i])[j]);
316 // str now contains one local IP address
319 // If an error occur r == -1
320 // Most of the time it will return 127.0.0.1...
326 * \brief Creates a new UID. As stipulate in the DICOM ref
327 * each time a DICOM image is create it should have
328 * a unique identifier (URI)
330 std::string Util::CreateUniqueUID(const std::string& root)
332 // The code works as follow:
333 // echo "gdcm" | od -b
334 // 0000000 147 144 143 155 012
335 // Therefore we return
336 // radical + 147.144.143.155 + IP + time()
337 std::string radical = root;
338 if( !root.size() ) //anything better ?
340 radical = "0.0."; // Is this really usefull ?
343 // A root was specified use it to forge our new UID:
344 radical += "147.144.143.155"; // gdcm
346 radical += Util::GetIPAddress();
348 radical += Util::GetCurrentDate();
350 radical += Util::GetCurrentTime();
356 std::ostream& binary_write(std::ostream& os, const T& val)
358 return os.write(reinterpret_cast<const char*>(&val), sizeof val);
361 std::ostream& binary_write(std::ostream& os, const uint16_t& val)
363 #ifdef GDCM_WORDS_BIGENDIAN
365 swap = ((( val << 8 ) & 0x0ff00 ) | (( val >> 8 ) & 0x00ff ) );
366 return os.write(reinterpret_cast<const char*>(&swap), 2);
368 return os.write(reinterpret_cast<const char*>(&val), 2);
369 #endif //GDCM_WORDS_BIGENDIAN
372 std::ostream& binary_write(std::ostream& os, const uint32_t& val)
374 #ifdef GDCM_WORDS_BIGENDIAN
376 swap = ( ((val<<24) & 0xff000000) | ((val<<8) & 0x00ff0000) |
377 ((val>>8) & 0x0000ff00) | ((val>>24) & 0x000000ff) );
378 return os.write(reinterpret_cast<const char*>(&swap), 4);
380 return os.write(reinterpret_cast<const char*>(&val), 4);
381 #endif //GDCM_WORDS_BIGENDIAN
384 std::ostream& binary_write(std::ostream& os, const char* val)
386 return os.write(val, strlen(val));
389 std::ostream& binary_write(std::ostream& os, std::string const & val)
391 return os.write(val.c_str(), val.size());
394 } // end namespace gdcm