]> Creatis software - bbtk.git/blob - packages/std/src/bbstdFilesFromDirectory.cxx
#2814 BBTK Bug New Normal std FilesFromDirectory box is not working in windows
[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 temp = dirName+fileName;
127          std::string::size_type spacePosition = temp.find_first_of(' ');
128                  if (spacePosition != std::string::npos) 
129          {
130    std::cout << "=========================================== File name : [" <<temp << 
131               "] contains space(s); Discarted !" << std::endl;
132             temp.insert(spacePosition, "\\");
133    continue;  /// \TODO : fix the trouble (vtk?)
134          }      
135          Filenames.push_back(temp);
136          numberOfFiles++;
137       }
138    }
139    DWORD dwError = GetLastError();
140    if (hFile != INVALID_HANDLE_VALUE) 
141       FindClose(hFile);
142    if (dwError != ERROR_NO_MORE_FILES) 
143    {
144       LPVOID lpMsgBuf;
145       FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|
146                     FORMAT_MESSAGE_FROM_SYSTEM|
147                     FORMAT_MESSAGE_IGNORE_INSERTS,
148                     NULL,GetLastError(),
149                     MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
150                     (LPTSTR) &lpMsgBuf,0,NULL);
151
152       //gdcmErrorMacro("FindNextFile error. Error is " << (char *)lpMsgBuf
153       //             <<" for the directory : "<<dirName);
154       return -1;
155    }
156
157 #else
158   // Real POSIX implementation: scandir is a BSD extension only, and doesn't 
159   // work on debian for example
160
161    DIR* dir = opendir(dirName.c_str());
162    if (!dir)
163    {
164       return 0;
165    }
166
167    // According to POSIX, the dirent structure contains a field char d_name[]
168    // of unspecified size, with at most NAME_MAX characters preceeding the
169    // terminating null character. Use of other fields will harm the  porta-
170    // bility of your programs.
171
172    struct stat buf;
173    dirent *d;
174    for (d = readdir(dir); d; d = readdir(dir))
175    {
176       fileName = dirName + d->d_name;
177       std::string temp = fileName;
178       if( stat(fileName.c_str(), &buf) != 0 )
179       {
180          //gdcmErrorMacro( strerror(errno) );
181       }
182       if ( S_ISREG(buf.st_mode) )    //is it a regular file?
183       {
184          if ( d->d_name[0]!='.')
185          {
186          
187              std::string::size_type /* long int */ spacePosition = temp.find_first_of(' ');
188              if (spacePosition != std::string::npos)
189              {
190    std::cout << "=========================================== File name : [" <<temp << 
191               "] contains space(s); Discarted !" << std::endl;
192                  temp.insert(spacePosition, "\\");
193    continue;   /// \TODO : fix the trouble (vtk?)
194              }
195              Filenames.push_back(temp);  
196              numberOfFiles++;
197          }
198       }
199       else if ( S_ISDIR(buf.st_mode) ) //directory?
200       {
201          if ( d->d_name[0] != '.' && recursive ) //we also skip hidden files
202          {
203             numberOfFiles += Explore( fileName, recursive);
204          }
205       }
206       else
207       {
208          //gdcmErrorMacro( "Unexpected error" );
209          return -1;
210       }
211    }
212    if( closedir(dir) != 0 )
213    {
214       //gdcmErrorMacro( strerror(errno) );
215    }
216 #endif
217
218   std::string tmpString;
219   int i,ii,sizeFilenames = Filenames.size();
220   for (i=0; i<sizeFilenames; i++)
221   {
222     for (ii=i; ii<sizeFilenames; ii++)
223     {
224         if (Filenames[i]>Filenames[ii]) 
225         {
226           tmpString=Filenames[i];
227           Filenames[i]=Filenames[ii];
228           Filenames[ii]=tmpString;
229         } // if 
230     } // for ii
231   } // for i
232
233   return numberOfFiles;
234 }
235
236
237 }
238 // EO namespace bbstd
239
240