]> Creatis software - bbtk.git/blob - packages/std/src/bbstdFilesFromDirectory.cxx
#2853 BBTK Feature New Normal std:FilesFromDirectory box add option to create list...
[bbtk.git] / packages / std / src / bbstdFilesFromDirectory.cxx
1 /*
2  # ---------------------------------------------------------------------
3  #
4  # Copyright (c) CREATIS (Centre de Recherche en Acquisition et Traitement de l'Image
5  #                        pour la SantÈ)
6  # Authors : Eduardo Davila, Frederic Cervenansky, Claire Mouton
7  # Previous Authors : Laurent Guigues, Jean-Pierre Roux
8  # CreaTools website : www.creatis.insa-lyon.fr/site/fr/creatools_accueil
9  #
10  #  This software is governed by the CeCILL-B license under French law and
11  #  abiding by the rules of distribution of free software. You can  use,
12  #  modify and/ or redistribute the software under the terms of the CeCILL-B
13  #  license as circulated by CEA, CNRS and INRIA at the following URL
14  #  http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html
15  #  or in the file LICENSE.txt.
16  #
17  #  As a counterpart to the access to the source code and  rights to copy,
18  #  modify and redistribute granted by the license, users are provided only
19  #  with a limited warranty  and the software's author,  the holder of the
20  #  economic rights,  and the successive licensors  have only  limited
21  #  liability.
22  #
23  #  The fact that you are presently reading this means that you have had
24  #  knowledge of the CeCILL-B license and that you accept its terms.
25  # ------------------------------------------------------------------------ */
26
27
28 #include "bbstdFilesFromDirectory.h"
29 #include "bbstdPackage.h"
30 #include <string>
31
32 #ifdef _MSC_VER
33    #include <windows.h>
34    #include <direct.h>
35 #else
36    #include <dirent.h>   
37    #include <sys/types.h>
38 #endif
39
40 #include <sys/stat.h>  //stat function
41
42 namespace bbstd
43 {
44
45 BBTK_ADD_BLACK_BOX_TO_PACKAGE(std,FilesFromDirectory)
46 BBTK_BLACK_BOX_IMPLEMENTATION(FilesFromDirectory,bbtk::AtomicBlackBox);
47
48 void FilesFromDirectory::Process()
49 {
50         Filenames.clear();
51         SimpleFilenames.clear();
52         DirName         = bbGetInputIn();
53         bool rec        = bbGetInputRecursive();
54         /*int nbFiles = */ Explore(DirName, rec);
55         CleanFilenames( bbGetInputIn() );
56         bbSetOutputOut(Filenames);   
57         bbSetOutputOutSimple(SimpleFilenames);   
58 }
59
60 void FilesFromDirectory::bbUserSetDefaultValues()
61 {
62     bbSetInputIn(".");
63     bbSetInputRecursive(false);  
64     bbSetInputType(0);  
65 }
66
67 void FilesFromDirectory::bbUserInitializeProcessing() 
68
69 }
70
71 void FilesFromDirectory::bbUserFinalizeProcessing() 
72 {
73 }
74   
75 /**
76  * \brief   Add a SEPARATOR to the end of the name if necessary
77  * @param   pathname file/directory name to normalize 
78  */
79 std::string FilesFromDirectory::NormalizePath(std::string const &pathname)
80 {
81 #ifdef _WIN32
82    const char FILESEPARATOR = '\\';
83 #else
84    const char FILESEPARATOR = '/';
85 #endif
86
87    std::string name = pathname;
88    int size = name.size();
89
90    if ( name[size-1] != FILESEPARATOR )
91    {
92       name += FILESEPARATOR;
93    }
94    return name;
95
96
97 /**
98  * \brief   Explores a directory with possibility of recursion
99  *          return number of files read
100  * @param  dirpath   directory to explore
101  * @param  recursive whether we want recursion or not
102  */
103
104
105
106 int FilesFromDirectory::Explore(std::string const &dirpath, bool recursive)
107 {
108         int numberOfFiles               = 0;
109         std::string dirName     = NormalizePath(dirpath);
110         int tmpNumberOfFiles;
111         std::string fileName;
112 #ifdef _MSC_VER
113         WIN32_FIND_DATA fileData;
114         //assert( dirName[dirName.size()-1] == '' );
115         HANDLE hFile = FindFirstFile((dirName+"*").c_str(), &fileData);
116
117         for(BOOL b = (hFile != INVALID_HANDLE_VALUE); b;
118        b = FindNextFile(hFile, &fileData))
119         {
120       fileName = fileData.cFileName;
121       if ( fileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
122       {
123          // Need to check for . and .. to avoid infinite loop
124          if ( fileName != "." && fileName != ".." && recursive )
125          {
126                         if (bbGetInputType()==1)
127                         {
128                         std::string temp = dirName+fileName;
129                         Filenames.push_back(temp);       
130                         numberOfFiles++;
131                         } // Type ALL_directories
132
133                         tmpNumberOfFiles        =       Explore(dirName+fileName, recursive);
134                         if ((bbGetInputType()==2)&&tmpNumberOfFiles==0)
135                         {
136                         std::string temp = dirName+fileName;
137                         Filenames.push_back(temp);       
138                         numberOfFiles++;
139                         } // Type Lsast_directories
140                         
141                         numberOfFiles           =       numberOfFiles + tmpNumberOfFiles;
142          } // if
143       } else  {
144 //      std::string temp = "\"" +dirName+fileName + "\"";
145         std::string temp = dirName+fileName;
146
147 /*
148         std::string::size_type spacePosition = temp.find_first_of(' ');
149                 if (spacePosition != std::string::npos) 
150                 {
151                         std::cout << "=========================================== File name : [" <<temp << 
152               "] contains space(s); Discarted !" << std::endl;
153                 temp.insert(spacePosition, "\\");
154                         continue;  /// \TODO : fix the trouble (vtk?)
155                 } // if !npos
156 */
157
158
159                 if (bbGetInputType()==0)
160                 {
161                         Filenames.push_back(temp);       
162                         numberOfFiles++;
163                 } // Type files
164
165       } // if !directory
166         } // for
167         DWORD dwError = GetLastError();
168         if (hFile != INVALID_HANDLE_VALUE) 
169         {
170                 FindClose(hFile);
171         }// hFile
172         if (dwError != ERROR_NO_MORE_FILES) 
173         {
174       LPVOID lpMsgBuf;
175       FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|
176                     FORMAT_MESSAGE_FROM_SYSTEM|
177                     FORMAT_MESSAGE_IGNORE_INSERTS,
178                     NULL,GetLastError(),
179                     MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
180                     (LPTSTR) &lpMsgBuf,0,NULL);
181
182       //gdcmErrorMacro("FindNextFile error. Error is " << (char *)lpMsgBuf
183       //             <<" for the directory : "<<dirName);
184       return -1;
185         } // dwError
186
187 #else
188   // Real POSIX implementation: scandir is a BSD extension only, and doesn't 
189   // work on debian for example
190
191         DIR* dir = opendir(dirName.c_str());
192         if (!dir)
193         {
194                 return 0;
195         }
196
197    // According to POSIX, the dirent structure contains a field char d_name[]
198    // of unspecified size, with at most NAME_MAX characters preceeding the
199    // terminating null character. Use of other fields will harm the  porta-
200    // bility of your programs.
201
202         struct stat     buf;
203         dirent                  *d;
204         for (d = readdir(dir); d; d = readdir(dir))
205         {
206         fileName = dirName + d->d_name;
207         std::string temp = fileName;
208         if( stat(fileName.c_str(), &buf) != 0 )
209         {
210                  //gdcmErrorMacro( strerror(errno) );
211         } // stat
212         if ( S_ISREG(buf.st_mode) )    //is it a regular file?
213         {
214                 if ( d->d_name[0]!='.')
215                 {
216
217 /*
218                         std::string::size_type  spacePosition = temp.find_first_of(' ');
219                 if (spacePosition != std::string::npos)
220                         {
221                                         std::cout << "=========================================== File name : [" <<temp << 
222                                 "] contains space(s); Discarted !" << std::endl;
223                         temp.insert(spacePosition, "\\");
224                                         continue;   /// \TODO : fix the trouble (vtk?)
225                 } // if spacePosition
226 */
227
228                                 if (bbGetInputType()==0)
229                                 {
230                         Filenames.push_back(temp);       
231                                 numberOfFiles++;
232                                 } // Type files
233                 } // d_name
234         } else if ( S_ISDIR(buf.st_mode) ) {  //directory?
235                 if ( d->d_name[0] != '.' && recursive ) //we also skip hidden files
236                 {
237                                 if (bbGetInputType()==1)
238                                 {
239                         Filenames.push_back(fileName);   
240                                 numberOfFiles++;
241                                 } // Type All_directories
242
243                                 tmpNumberOfFiles        = Explore( fileName, recursive);
244                                 if ((bbGetInputType()==2)&&tmpNumberOfFiles==0)
245                                 {
246                                         Filenames.push_back(fileName);   
247                                 numberOfFiles++;
248                                 } // Type Lsast_directories
249                         numberOfFiles           = numberOfFiles+tmpNumberOfFiles;
250                 } // d_name
251                 } else {
252                 //gdcmErrorMacro( "Unexpected error" );
253                 return -1;
254         } // Regular FILE
255    }
256    if( closedir(dir) != 0 )
257    {
258       //gdcmErrorMacro( strerror(errno) );
259    }// closedir
260 #endif
261
262
263         return numberOfFiles;
264 }
265
266
267 //------------------------------------------------------------------------------
268 void FilesFromDirectory::CleanFilenames( std::string basePath )
269 {
270         std::string tmpString;
271         int i,ii,sizeFilenames = Filenames.size();
272
273
274 // Cleanning paths with spaces  
275         for (i=0; i<sizeFilenames; i++)
276         {
277                 tmpString=Filenames[i];
278                 std::string::size_type  spacePosition = tmpString.find_first_of(' ');
279                 if (spacePosition != std::string::npos)
280                 {
281                         std::cout << "=========================================== File name : [" <<tmpString << 
282                 "] contains space(s); Discarted !" << std::endl;
283                         tmpString.insert(spacePosition, "\\");
284                         Filenames[i]=tmpString;
285 //                      continue;   /// \TODO : fix the trouble (vtk?)
286                 } // if spacePosition
287         }
288
289 // Alphabetical order   
290         for (i=0; i<sizeFilenames; i++)
291         {
292         for (ii=i; ii<sizeFilenames; ii++)
293                 {
294                         if (Filenames[i]>Filenames[ii]) 
295                 {
296                         tmpString=Filenames[i];
297                         Filenames[i]=Filenames[ii];
298                         Filenames[ii]=tmpString;
299                 } // if 
300         } // for ii
301         } // for i
302
303 // Creating SimpleFilenames
304         unsigned int lenghtBasePath = basePath.length();
305         for (i=0; i<sizeFilenames; i++)
306         {
307
308                 SimpleFilenames.push_back( Filenames[i].substr( lenghtBasePath ) );
309         } // for i
310
311 }
312
313
314
315
316 /*
317
318 int FilesFromDirectory::Explore(std::string const &dirpath, bool recursive)
319 {
320    Filenames.clear();
321    int numberOfFiles = 0;
322    std::string fileName;
323    std::string dirName = NormalizePath(dirpath);
324 #ifdef _MSC_VER
325    WIN32_FIND_DATA fileData;
326    //assert( dirName[dirName.size()-1] == '' );
327    HANDLE hFile = FindFirstFile((dirName+"*").c_str(), &fileData);
328
329    for(BOOL b = (hFile != INVALID_HANDLE_VALUE); b;
330        b = FindNextFile(hFile, &fileData))
331    {
332       fileName = fileData.cFileName;
333       if ( fileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
334       {
335          // Need to check for . and .. to avoid infinite loop
336          if ( fileName != "." && fileName != ".." && recursive )
337          {
338             numberOfFiles += Explore(dirName+fileName, recursive);
339          }
340       }
341       else
342       {
343 //         std::string temp = "\"" +dirName+fileName + "\"";
344          std::string temp = dirName+fileName;
345          std::string::size_type spacePosition = temp.find_first_of(' ');
346                  if (spacePosition != std::string::npos) 
347          {
348    std::cout << "=========================================== File name : [" <<temp << 
349               "] contains space(s); Discarted !" << std::endl;
350             temp.insert(spacePosition, "\\");
351    continue;  /// \TODO : fix the trouble (vtk?)
352          }      
353          Filenames.push_back(temp);
354          numberOfFiles++;
355       }
356    }
357    DWORD dwError = GetLastError();
358    if (hFile != INVALID_HANDLE_VALUE) 
359       FindClose(hFile);
360    if (dwError != ERROR_NO_MORE_FILES) 
361    {
362       LPVOID lpMsgBuf;
363       FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|
364                     FORMAT_MESSAGE_FROM_SYSTEM|
365                     FORMAT_MESSAGE_IGNORE_INSERTS,
366                     NULL,GetLastError(),
367                     MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
368                     (LPTSTR) &lpMsgBuf,0,NULL);
369
370       //gdcmErrorMacro("FindNextFile error. Error is " << (char *)lpMsgBuf
371       //             <<" for the directory : "<<dirName);
372       return -1;
373    }
374
375 #else
376   // Real POSIX implementation: scandir is a BSD extension only, and doesn't 
377   // work on debian for example
378
379    DIR* dir = opendir(dirName.c_str());
380    if (!dir)
381    {
382       return 0;
383    }
384
385    // According to POSIX, the dirent structure contains a field char d_name[]
386    // of unspecified size, with at most NAME_MAX characters preceeding the
387    // terminating null character. Use of other fields will harm the  porta-
388    // bility of your programs.
389
390    struct stat buf;
391    dirent *d;
392    for (d = readdir(dir); d; d = readdir(dir))
393    {
394       fileName = dirName + d->d_name;
395       std::string temp = fileName;
396       if( stat(fileName.c_str(), &buf) != 0 )
397       {
398          //gdcmErrorMacro( strerror(errno) );
399       }
400       if ( S_ISREG(buf.st_mode) )    //is it a regular file?
401       {
402          if ( d->d_name[0]!='.')
403          {
404          
405              std::string::size_type  spacePosition = temp.find_first_of(' ');
406              if (spacePosition != std::string::npos)
407              {
408    std::cout << "=========================================== File name : [" <<temp << 
409               "] contains space(s); Discarted !" << std::endl;
410                  temp.insert(spacePosition, "\\");
411    continue;   /// \TODO : fix the trouble (vtk?)
412              }
413              Filenames.push_back(temp);  
414              numberOfFiles++;
415          }
416       }
417       else if ( S_ISDIR(buf.st_mode) ) //directory?
418       {
419          if ( d->d_name[0] != '.' && recursive ) //we also skip hidden files
420          {
421             numberOfFiles += Explore( fileName, recursive);
422          }
423       }
424       else
425       {
426          //gdcmErrorMacro( "Unexpected error" );
427          return -1;
428       }
429    }
430    if( closedir(dir) != 0 )
431    {
432       //gdcmErrorMacro( strerror(errno) );
433    }
434 #endif
435
436   std::string tmpString;
437   int i,ii,sizeFilenames = Filenames.size();
438   for (i=0; i<sizeFilenames; i++)
439   {
440     for (ii=i; ii<sizeFilenames; ii++)
441     {
442         if (Filenames[i]>Filenames[ii]) 
443         {
444           tmpString=Filenames[i];
445           Filenames[i]=Filenames[ii];
446           Filenames[ii]=tmpString;
447         } // if 
448     } // for ii
449   } // for i
450
451   return numberOfFiles;
452 }
453 */
454
455 }
456 // EO namespace bbstd
457
458