]> Creatis software - gdcm.git/blob - src/gdcmUtil.cxx
ENH: Commiting 1/2 patch from Jean Michel Rouet, for better DICOM writting support
[gdcm.git] / src / gdcmUtil.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmUtil.cxx,v $
5   Language:  C++
6   Date:      $Date: 2004/11/10 18:27:24 $
7   Version:   $Revision: 1.61 $
8                                                                                 
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.
12                                                                                 
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.
16                                                                                 
17 =========================================================================*/
18
19 #include "gdcmUtil.h"
20 #include "gdcmDebug.h"
21
22 // For GetCurrentDate, GetCurrentTime
23 #include <time.h>
24 #include <sys/types.h>
25 #include <sys/stat.h>
26
27 #include <stdarg.h>  //only included in implementation file
28 #include <stdio.h>   //only included in implementation file
29
30 namespace gdcm 
31 {
32
33 /**
34  * \ingroup Globals
35  * \brief Provide a better 'c++' approach for sprintf
36  * For example c code is:
37  * sprintf(trash, "%04x|%04x", group , element);
38  *
39  * c++ is 
40  * std::ostringstream buf;
41  * buf << std::right << std::setw(4) << std::setfill('0') << std::hex
42  *     << group << "|" << std::right << std::setw(4) << std::setfill('0') 
43  *     << std::hex <<  element;
44  * buf.str();
45  */
46
47 std::string Util::Format(const char* format, ...)
48 {
49    char buffer[2048];
50    va_list args;
51    va_start(args, format);
52    vsprintf(buffer, format, args);  //might be a security flaw
53    return buffer;
54 }
55
56
57 /**
58  * \ingroup Globals
59  * \brief Because not available in C++ (?)
60  */
61 void Util::Tokenize (const std::string& str,
62                      std::vector<std::string>& tokens,
63                      const std::string& delimiters)
64 {
65    std::string::size_type lastPos = str.find_first_not_of(delimiters,0);
66    std::string::size_type pos     = str.find_first_of    (delimiters,lastPos);
67    while (std::string::npos != pos || std::string::npos != lastPos)
68    {
69       tokens.push_back(str.substr(lastPos, pos - lastPos));
70       lastPos = str.find_first_not_of(delimiters, pos);
71       pos     = str.find_first_of    (delimiters, lastPos);
72    }
73 }
74
75 /**
76  * \ingroup Globals
77  * \brief Because not available in C++ (?)
78  *        Counts the number of occurences of a substring within a string
79  */
80  
81 int Util::CountSubstring (const std::string& str,
82                           const std::string& subStr)
83 {
84    int count = 0;   // counts how many times it appears
85    unsigned int x = 0;       // The index position in the string
86
87    do
88    {
89       x = str.find(subStr,x);       // Find the substring
90       if (x != std::string::npos)   // If present
91       {
92          count++;                  // increase the count
93          x += subStr.length();     // Skip this word
94       }
95    }
96    while (x != std::string::npos);  // Carry on until not present
97
98    return count;
99 }
100
101 /**
102  * \ingroup Globals
103  * \brief  Weed out a string from the non-printable characters (in order
104  *         to avoid corrupting the terminal of invocation when printing)
105  * @param s string to remove non printable characters from
106  */
107 std::string Util::CreateCleanString(std::string const & s)
108 {
109    std::string str = s;
110
111    for(unsigned int i=0;i<str.size();i++)
112    {
113       if(!isprint(str[i]))
114       {
115          str[i]='.';
116       }
117    }
118
119    if(str.size()>0)
120    {
121       if(!isprint(s[str.size()-1]))
122       {
123          if(s[str.size()-1]==0)
124          {
125             str[str.size()-1]=' ';
126          }
127       }
128    }
129
130    return str;
131 }
132
133 /**
134  * \ingroup Globals
135  * \brief   Add a SEPARATOR to the end of the name is necessary
136  * @param name file/directory name to normalize 
137  */
138 std::string Util::NormalizePath(std::string const & pathname)
139 {
140    const char SEPARATOR_X      = '/';
141    const char SEPARATOR_WIN    = '\\';
142    const std::string SEPARATOR = "/";
143    std::string name = pathname;
144    int size = name.size();
145
146    if( name[size-1] != SEPARATOR_X && name[size-1] != SEPARATOR_WIN )
147    {
148       name += SEPARATOR;
149    }
150    return name;
151 }
152
153 /**
154  * \ingroup Globals
155  * \brief   Get the (directory) path from a full path file name
156  * @param   fullName file/directory name to extract Path from
157  */
158 std::string Util::GetPath(std::string const & fullName)
159 {
160    std::string res = fullName;
161    int pos1 = res.rfind("/");
162    int pos2 = res.rfind("\\");
163    if( pos1 > pos2)
164    {
165       res.resize(pos1);
166    }
167    else
168    {
169       res.resize(pos2);
170    }
171
172    return res;
173 }
174
175 /**
176  * \ingroup Util
177  * \brief   Get the (last) name of a full path file name
178  * @param   fullName file/directory name to extract end name from
179  */
180 std::string Util::GetName(std::string const & fullName)
181 {   
182   std::string filename = fullName;
183
184   std::string::size_type slash_pos = filename.rfind("/");
185   std::string::size_type backslash_pos = filename.rfind("\\");
186   slash_pos = slash_pos > backslash_pos ? slash_pos : backslash_pos;
187   if(slash_pos != std::string::npos)
188     {
189     return filename.substr(slash_pos + 1);
190     }
191   else
192     {
193     return filename;
194     }
195
196
197 /**
198  * \ingroup Util
199  * \brief Create a /DICOM/ string:
200  * It should a of even lenght (no odd length ever)
201  * It can contains as many \0 as you want.
202  * This function is similar to DicomString(const char*), 
203  * except it doesn't take a lenght. 
204  * It only pad with a null character if length is odd
205  */
206 std::string Util::DicomString(const char* s)
207 {
208    size_t l = strlen(s);
209    if( l%2 )
210    {
211       l++;
212    }
213    std::string r(s, s+l);
214    assert( !(r.size() % 2) );
215    return r;
216 }
217
218 /**
219  * \ingroup Util
220  * \brief   Get the current date of the system in a dicom string
221  */
222 std::string Util::GetCurrentDate()
223 {
224     char tmp[512];
225     time_t tloc;
226     time (&tloc);    
227     strftime(tmp,512,"%Y%m%d", localtime(&tloc) );
228     return tmp;
229 }
230
231 /**
232  * \ingroup Util
233  * \brief   Get the current time of the system in a dicom string
234  */
235 std::string Util::GetCurrentTime()
236 {
237     char tmp[512];
238     time_t tloc;
239     time (&tloc);
240     strftime(tmp,512,"%H%M%S", localtime(&tloc) );
241     return tmp;  
242 }
243
244
245
246 /**
247  * \ingroup Util
248  * \brief Create a /DICOM/ string:
249  * It should a of even length (no odd length ever)
250  * It can contains as many \0 as you want.
251  */
252 std::string Util::DicomString(const char* s, size_t l)
253 {
254    std::string r(s, s+l);
255    assert( !(r.size() % 2) );
256    return r;
257 }
258
259 template <class T>
260 std::ostream& binary_write(std::ostream& os, const T& val)
261 {
262     return os.write(reinterpret_cast<const char*>(&val), sizeof val);
263 }
264
265 std::ostream& binary_write(std::ostream& os, const uint16_t& val)
266 {
267 #ifdef GDCM_WORDS_BIGENDIAN
268     uint16_t swap;
269     swap = ((( val << 8 ) & 0x0ff00 ) | (( val >> 8 ) & 0x00ff ) );
270     return os.write(reinterpret_cast<const char*>(&swap), 2);
271 #else
272     return os.write(reinterpret_cast<const char*>(&val), 2);
273 #endif //GDCM_WORDS_BIGENDIAN
274 }
275
276 std::ostream& binary_write(std::ostream& os, const uint32_t& val)
277 {
278 #ifdef GDCM_WORDS_BIGENDIAN
279     uint32_t swap;
280     swap = ( ((val<<24) & 0xff000000) | ((val<<8)  & 0x00ff0000) | 
281              ((val>>8)  & 0x0000ff00) | ((val>>24) & 0x000000ff) );
282     return os.write(reinterpret_cast<const char*>(&swap), 4);
283 #else
284     return os.write(reinterpret_cast<const char*>(&val), 4);
285 #endif //GDCM_WORDS_BIGENDIAN
286 }
287
288 //template <>
289 std::ostream& binary_write(std::ostream& os, const char* val)
290 {
291     return os.write(val, strlen(val));
292 }
293
294 std::ostream& binary_write(std::ostream& os, std::string const & val)
295 {
296     return os.write(val.c_str(), val.size());
297 }
298
299
300 } // end namespace gdcm
301