2 # ---------------------------------------------------------------------
4 # Copyright (c) CREATIS (Centre de Recherche en Acquisition et Traitement de l'Image
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
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.
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
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 # ------------------------------------------------------------------------ */
28 #include "bbstdFilesFromDirectory.h"
29 #include "bbstdPackage.h"
37 #include <sys/types.h>
40 #include <sys/stat.h> //stat function
45 BBTK_ADD_BLACK_BOX_TO_PACKAGE(std,FilesFromDirectory)
46 BBTK_BLACK_BOX_IMPLEMENTATION(FilesFromDirectory,bbtk::AtomicBlackBox);
48 void FilesFromDirectory::Process()
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);
60 void FilesFromDirectory::bbUserSetDefaultValues()
63 bbSetInputRecursive(false);
67 void FilesFromDirectory::bbUserInitializeProcessing()
71 void FilesFromDirectory::bbUserFinalizeProcessing()
76 * \brief Add a SEPARATOR to the end of the name if necessary
77 * @param pathname file/directory name to normalize
79 std::string FilesFromDirectory::NormalizePath(std::string const &pathname)
82 const char FILESEPARATOR = '\\';
84 const char FILESEPARATOR = '/';
87 std::string name = pathname;
88 int size = name.size();
90 if ( name[size-1] != FILESEPARATOR )
92 name += FILESEPARATOR;
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
106 int FilesFromDirectory::Explore(std::string const &dirpath, bool recursive)
108 int numberOfFiles = 0;
109 std::string dirName = NormalizePath(dirpath);
110 int tmpNumberOfFiles;
111 std::string fileName;
113 WIN32_FIND_DATA fileData;
114 //assert( dirName[dirName.size()-1] == '' );
115 HANDLE hFile = FindFirstFile((dirName+"*").c_str(), &fileData);
117 for(BOOL b = (hFile != INVALID_HANDLE_VALUE); b;
118 b = FindNextFile(hFile, &fileData))
120 fileName = fileData.cFileName;
121 if ( fileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
123 // Need to check for . and .. to avoid infinite loop
124 if ( fileName != "." && fileName != ".." && recursive )
126 if (bbGetInputType()==1)
128 std::string temp = dirName+fileName;
129 Filenames.push_back(temp);
131 } // Type ALL_directories
133 tmpNumberOfFiles = Explore(dirName+fileName, recursive);
134 if ((bbGetInputType()==2)&&tmpNumberOfFiles==0)
136 std::string temp = dirName+fileName;
137 Filenames.push_back(temp);
139 } // Type Lsast_directories
141 numberOfFiles = numberOfFiles + tmpNumberOfFiles;
143 if ( fileName != "." && fileName != ".." && !recursive )
144 if ((bbGetInputType()==1) || (bbGetInputType()==2))
146 std::string temp = dirName+fileName;
147 Filenames.push_back(temp);
149 } // Type All_directories
150 }// fileName && !recursive
152 // std::string temp = "\"" +dirName+fileName + "\"";
153 std::string temp = dirName+fileName;
156 std::string::size_type spacePosition = temp.find_first_of(' ');
157 if (spacePosition != std::string::npos)
159 std::cout << "=========================================== File name : [" <<temp <<
160 "] contains space(s); Discarted !" << std::endl;
161 temp.insert(spacePosition, "\\");
162 continue; /// \TODO : fix the trouble (vtk?)
167 if (bbGetInputType()==0)
169 Filenames.push_back(temp);
175 DWORD dwError = GetLastError();
176 if (hFile != INVALID_HANDLE_VALUE)
180 if (dwError != ERROR_NO_MORE_FILES)
183 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|
184 FORMAT_MESSAGE_FROM_SYSTEM|
185 FORMAT_MESSAGE_IGNORE_INSERTS,
187 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
188 (LPTSTR) &lpMsgBuf,0,NULL);
190 //gdcmErrorMacro("FindNextFile error. Error is " << (char *)lpMsgBuf
191 // <<" for the directory : "<<dirName);
196 // Real POSIX implementation: scandir is a BSD extension only, and doesn't
197 // work on debian for example
199 DIR* dir = opendir( dirName.c_str() );
205 // According to POSIX, the dirent structure contains a field char d_name[]
206 // of unspecified size, with at most NAME_MAX characters preceeding the
207 // terminating null character. Use of other fields will harm the porta-
208 // bility of your programs.
212 for (d = readdir(dir); d; d = readdir(dir))
214 fileName = dirName + d->d_name;
215 std::string temp = fileName;
216 if( stat(fileName.c_str(), &buf) != 0 )
218 //gdcmErrorMacro( strerror(errno) );
220 if ( S_ISREG(buf.st_mode) ) //is it a regular file?
222 if ( d->d_name[0]!='.')
226 std::string::size_type spacePosition = temp.find_first_of(' ');
227 if (spacePosition != std::string::npos)
229 std::cout << "=========================================== File name : [" <<temp <<
230 "] contains space(s); Discarted !" << std::endl;
231 temp.insert(spacePosition, "\\");
232 continue; /// \TODO : fix the trouble (vtk?)
233 } // if spacePosition
236 if (bbGetInputType()==0)
238 Filenames.push_back(temp);
242 } else if ( S_ISDIR(buf.st_mode) ) { //directory?
243 if ( (d->d_name[0]!='.') && recursive ) //we also skip hidden files
245 if (bbGetInputType()==1)
247 Filenames.push_back(fileName);
249 } // Type All_directories
251 tmpNumberOfFiles = Explore( fileName, recursive);
252 if ((bbGetInputType()==2)&&tmpNumberOfFiles==0)
254 Filenames.push_back(fileName);
256 } // Type Lsast_directories
257 numberOfFiles = numberOfFiles+tmpNumberOfFiles;
258 }// d_name && recursive
259 if ( (d->d_name[0]!='.') && !recursive ) { //we also skip hidden files
260 if ((bbGetInputType()==1) || (bbGetInputType()==2))
262 Filenames.push_back(fileName);
264 } // Type All_directories
266 }// d_name && !recursive
269 //gdcmErrorMacro( "Unexpected error" );
273 if( closedir(dir) != 0 )
275 //gdcmErrorMacro( strerror(errno) );
280 return numberOfFiles;
284 //------------------------------------------------------------------------------
285 void FilesFromDirectory::CleanFilenames( std::string basePath )
287 std::string tmpString;
288 int i,ii,sizeFilenames = Filenames.size();
289 int j,sizeFileEnd = bbGetInputFileEnd().size();
293 //Selecting just the files in the FileEnd List
294 if (bbGetInputFileEnd().size()!=0)
296 for (i=sizeFilenames-1; i>=0; i--)
299 for (j=0; j<sizeFileEnd; j++)
301 std::string tmp=Filenames[i].substr( (Filenames[i].length()) - (bbGetInputFileEnd()[j]).length() ) ;
302 if (bbGetInputFileEnd()[j].compare( tmp )==0 )
308 if (okEraseElement==0)
310 Filenames.erase( Filenames.begin()+i );
315 sizeFilenames = Filenames.size();
317 // Cleanning paths with spaces
318 for (i=0; i<sizeFilenames; i++)
320 tmpString=Filenames[i];
322 std::string::size_type spacePosition = tmpString.find_first_of(' ');
323 if (spacePosition != std::string::npos)
325 std::cout << "=========================================== File name : [" <<tmpString <<
326 "] contains space(s); Discarted !" << std::endl;
327 tmpString.insert(spacePosition, "\\");
328 Filenames[i]=tmpString;
329 // continue; /// \TODO : fix the trouble (vtk?)
330 } // if spacePosition
334 // Alphabetical order
335 for (i=0; i<sizeFilenames; i++)
337 for (ii=i; ii<sizeFilenames; ii++)
339 if (Filenames[i]>Filenames[ii])
341 tmpString=Filenames[i];
342 Filenames[i]=Filenames[ii];
343 Filenames[ii]=tmpString;
348 // Creating SimpleFilenames
349 unsigned int lenghtBasePath = basePath.length();
350 for (i=0; i<sizeFilenames; i++)
352 SimpleFilenames.push_back( Filenames[i].substr( lenghtBasePath ) );
362 int FilesFromDirectory::Explore(std::string const &dirpath, bool recursive)
365 int numberOfFiles = 0;
366 std::string fileName;
367 std::string dirName = NormalizePath(dirpath);
369 WIN32_FIND_DATA fileData;
370 //assert( dirName[dirName.size()-1] == '' );
371 HANDLE hFile = FindFirstFile((dirName+"*").c_str(), &fileData);
373 for(BOOL b = (hFile != INVALID_HANDLE_VALUE); b;
374 b = FindNextFile(hFile, &fileData))
376 fileName = fileData.cFileName;
377 if ( fileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
379 // Need to check for . and .. to avoid infinite loop
380 if ( fileName != "." && fileName != ".." && recursive )
382 numberOfFiles += Explore(dirName+fileName, recursive);
387 // std::string temp = "\"" +dirName+fileName + "\"";
388 std::string temp = dirName+fileName;
389 std::string::size_type spacePosition = temp.find_first_of(' ');
390 if (spacePosition != std::string::npos)
392 std::cout << "=========================================== File name : [" <<temp <<
393 "] contains space(s); Discarted !" << std::endl;
394 temp.insert(spacePosition, "\\");
395 continue; /// \TODO : fix the trouble (vtk?)
397 Filenames.push_back(temp);
401 DWORD dwError = GetLastError();
402 if (hFile != INVALID_HANDLE_VALUE)
404 if (dwError != ERROR_NO_MORE_FILES)
407 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|
408 FORMAT_MESSAGE_FROM_SYSTEM|
409 FORMAT_MESSAGE_IGNORE_INSERTS,
411 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
412 (LPTSTR) &lpMsgBuf,0,NULL);
414 //gdcmErrorMacro("FindNextFile error. Error is " << (char *)lpMsgBuf
415 // <<" for the directory : "<<dirName);
420 // Real POSIX implementation: scandir is a BSD extension only, and doesn't
421 // work on debian for example
423 DIR* dir = opendir(dirName.c_str());
429 // According to POSIX, the dirent structure contains a field char d_name[]
430 // of unspecified size, with at most NAME_MAX characters preceeding the
431 // terminating null character. Use of other fields will harm the porta-
432 // bility of your programs.
436 for (d = readdir(dir); d; d = readdir(dir))
438 fileName = dirName + d->d_name;
439 std::string temp = fileName;
440 if( stat(fileName.c_str(), &buf) != 0 )
442 //gdcmErrorMacro( strerror(errno) );
444 if ( S_ISREG(buf.st_mode) ) //is it a regular file?
446 if ( d->d_name[0]!='.')
449 std::string::size_type spacePosition = temp.find_first_of(' ');
450 if (spacePosition != std::string::npos)
452 std::cout << "=========================================== File name : [" <<temp <<
453 "] contains space(s); Discarted !" << std::endl;
454 temp.insert(spacePosition, "\\");
455 continue; /// \TODO : fix the trouble (vtk?)
457 Filenames.push_back(temp);
461 else if ( S_ISDIR(buf.st_mode) ) //directory?
463 if ( d->d_name[0] != '.' && recursive ) //we also skip hidden files
465 numberOfFiles += Explore( fileName, recursive);
470 //gdcmErrorMacro( "Unexpected error" );
474 if( closedir(dir) != 0 )
476 //gdcmErrorMacro( strerror(errno) );
480 std::string tmpString;
481 int i,ii,sizeFilenames = Filenames.size();
482 for (i=0; i<sizeFilenames; i++)
484 for (ii=i; ii<sizeFilenames; ii++)
486 if (Filenames[i]>Filenames[ii])
488 tmpString=Filenames[i];
489 Filenames[i]=Filenames[ii];
490 Filenames[ii]=tmpString;
495 return numberOfFiles;
500 // EO namespace bbstd