]> Creatis software - bbtk.git/blob - packages/std/src/bbstdFilesFromDirectory.cxx
b85757fc528d0fafb85b0bf7b6eb03a138f6aa2c
[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    DirName = bbGetInputIn();
51    bool rec = bbGetInputRecursive();
52    /*int nbFiles = */ Explore(DirName, rec);
53    bbSetOutputOut(Filenames);   
54    
55 //  for (int i=0; i<Filenames.size(); i++)
56 //     std::cout << "Filenames [" << i << "] = [" << Filenames[i] << "]" << std::endl;  
57 }
58
59 void FilesFromDirectory::bbUserSetDefaultValues()
60 {
61     bbSetInputIn(".");
62     bbSetInputRecursive(false);  
63 }
64
65 void FilesFromDirectory::bbUserInitializeProcessing() 
66
67 }
68
69 void FilesFromDirectory::bbUserFinalizeProcessing() 
70 {
71 }
72   
73 /**
74  * \brief   Add a SEPARATOR to the end of the name if necessary
75  * @param   pathname file/directory name to normalize 
76  */
77 std::string FilesFromDirectory::NormalizePath(std::string const &pathname)
78 {
79 #ifdef _WIN32
80    const char FILESEPARATOR = '\\';
81 #else
82    const char FILESEPARATOR = '/';
83 #endif
84
85    std::string name = pathname;
86    int size = name.size();
87
88    if ( name[size-1] != FILESEPARATOR )
89    {
90       name += FILESEPARATOR;
91    }
92    return name;
93
94
95 /**
96  * \brief   Explores a directory with possibility of recursion
97  *          return number of files read
98  * @param  dirpath   directory to explore
99  * @param  recursive whether we want recursion or not
100  */
101 int FilesFromDirectory::Explore(std::string const &dirpath, bool recursive)
102 {
103    int numberOfFiles = 0;
104    std::string fileName;
105    std::string dirName = NormalizePath(dirpath);
106 #ifdef _MSC_VER
107    WIN32_FIND_DATA fileData;
108    //assert( dirName[dirName.size()-1] == '' );
109    HANDLE hFile = FindFirstFile((dirName+"*").c_str(), &fileData);
110
111    for(BOOL b = (hFile != INVALID_HANDLE_VALUE); b;
112        b = FindNextFile(hFile, &fileData))
113    {
114       fileName = fileData.cFileName;
115       if ( fileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
116       {
117          // Need to check for . and .. to avoid infinite loop
118          if ( fileName != "." && fileName != ".." && recursive )
119          {
120             numberOfFiles += Explore(dirName+fileName, recursive);
121          }
122       }
123       else
124       {
125          std::string temp = "\"" +dirName+fileName + "\"";
126          std::string::size_type spacePosition = temp.find_first_of(' ');
127                  if (spacePosition != std::string::npos) 
128          {
129    std::cout << "=========================================== File name : [" <<temp << 
130               "] contains space(s); Discarted !" << std::endl;
131             temp.insert(spacePosition, "\\");
132    continue;  /// \TODO : fix the trouble (vtk?)
133          }      
134          Filenames.push_back(temp);
135          numberOfFiles++;
136       }
137    }
138    DWORD dwError = GetLastError();
139    if (hFile != INVALID_HANDLE_VALUE) 
140       FindClose(hFile);
141    if (dwError != ERROR_NO_MORE_FILES) 
142    {
143       LPVOID lpMsgBuf;
144       FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|
145                     FORMAT_MESSAGE_FROM_SYSTEM|
146                     FORMAT_MESSAGE_IGNORE_INSERTS,
147                     NULL,GetLastError(),
148                     MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
149                     (LPTSTR) &lpMsgBuf,0,NULL);
150
151       //gdcmErrorMacro("FindNextFile error. Error is " << (char *)lpMsgBuf
152       //             <<" for the directory : "<<dirName);
153       return -1;
154    }
155
156 #else
157   // Real POSIX implementation: scandir is a BSD extension only, and doesn't 
158   // work on debian for example
159
160    DIR* dir = opendir(dirName.c_str());
161    if (!dir)
162    {
163       return 0;
164    }
165
166    // According to POSIX, the dirent structure contains a field char d_name[]
167    // of unspecified size, with at most NAME_MAX characters preceeding the
168    // terminating null character. Use of other fields will harm the  porta-
169    // bility of your programs.
170
171    struct stat buf;
172    dirent *d;
173    for (d = readdir(dir); d; d = readdir(dir))
174    {
175       fileName = dirName + d->d_name;
176       std::string temp = fileName;
177       if( stat(fileName.c_str(), &buf) != 0 )
178       {
179          //gdcmErrorMacro( strerror(errno) );
180       }
181       if ( S_ISREG(buf.st_mode) )    //is it a regular file?
182       {
183          if ( d->d_name[0]!='.')
184          {
185          
186              std::string::size_type /* long int */ spacePosition = temp.find_first_of(' ');
187              if (spacePosition != std::string::npos)
188              {
189    std::cout << "=========================================== File name : [" <<temp << 
190               "] contains space(s); Discarted !" << std::endl;
191                  temp.insert(spacePosition, "\\");
192    continue;   /// \TODO : fix the trouble (vtk?)
193              }
194              Filenames.push_back(temp);  
195              numberOfFiles++;
196          }
197       }
198       else if ( S_ISDIR(buf.st_mode) ) //directory?
199       {
200          if ( d->d_name[0] != '.' && recursive ) //we also skip hidden files
201          {
202             numberOfFiles += Explore( fileName, recursive);
203          }
204       }
205       else
206       {
207          //gdcmErrorMacro( "Unexpected error" );
208          return -1;
209       }
210    }
211    if( closedir(dir) != 0 )
212    {
213       //gdcmErrorMacro( strerror(errno) );
214    }
215 #endif
216
217   std::string tmpString;
218   int i,ii,sizeFilenames = Filenames.size();
219   for (i=0; i<sizeFilenames; i++)
220   {
221     for (ii=i; ii<sizeFilenames; ii++)
222     {
223         if (Filenames[i]>Filenames[ii]) 
224         {
225           tmpString=Filenames[i];
226           Filenames[i]=Filenames[ii];
227           Filenames[ii]=tmpString;
228         } // if 
229     } // for ii
230   } // for i
231
232   return numberOfFiles;
233 }
234
235
236 }
237 // EO namespace bbstd
238
239