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 /*int nbFiles = */ Explore(DirName, bbGetInputRecursive(), bbGetInputRecursiveLevel() );
54 CleanFilenames( DirName );
55 bbSetOutputOut(Filenames);
56 bbSetOutputOutSimple(SimpleFilenames);
59 void FilesFromDirectory::bbUserSetDefaultValues()
62 bbSetInputRecursive(false);
64 bbSetInputRecursiveLevel(999);
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]=='/')||(name[size-1]=='\\')))
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, int recursiveLevel)
108 int numberOfFiles = 0;
110 if (recursiveLevel>=0){
112 std::string dirName = NormalizePath(dirpath);
113 int tmpNumberOfFiles;
114 std::string fileName;
116 WIN32_FIND_DATA fileData;
117 //assert( dirName[dirName.size()-1] == '' );
118 HANDLE hFile = FindFirstFile((dirName+"*").c_str(), &fileData);
120 for(BOOL b = (hFile != INVALID_HANDLE_VALUE); b;
121 b = FindNextFile(hFile, &fileData))
123 fileName = fileData.cFileName;
124 if ( fileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
126 // Need to check for . and .. to avoid infinite loop
127 if ( fileName != "." && fileName != ".." && recursive )
129 if (bbGetInputType()==1)
131 std::string temp = dirName+fileName;
132 Filenames.push_back(temp);
134 } // Type ALL_directories
136 tmpNumberOfFiles = Explore(dirName+fileName, recursive,recursiveLevel-1);
137 if ((bbGetInputType()==2)&&tmpNumberOfFiles==0)
139 std::string temp = dirName+fileName;
140 Filenames.push_back(temp);
142 } // Type Lsast_directories
144 numberOfFiles = numberOfFiles + tmpNumberOfFiles;
146 if ( fileName != "." && fileName != ".." && !recursive )
148 if ((bbGetInputType()==1) || (bbGetInputType()==2))
150 std::string temp = dirName+fileName;
151 Filenames.push_back(temp);
153 } // Type All_directories
154 }// fileName && !recursive
156 // std::string temp = "\"" +dirName+fileName + "\"";
157 std::string temp = dirName+fileName;
160 std::string::size_type spacePosition = temp.find_first_of(' ');
161 if (spacePosition != std::string::npos)
163 std::cout << "=========================================== File name : [" <<temp <<
164 "] contains space(s); Discarted !" << std::endl;
165 temp.insert(spacePosition, "\\");
166 continue; /// \TODO : fix the trouble (vtk?)
171 if (bbGetInputType()==0)
173 Filenames.push_back(temp);
179 DWORD dwError = GetLastError();
180 if (hFile != INVALID_HANDLE_VALUE)
184 if (dwError != ERROR_NO_MORE_FILES)
187 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|
188 FORMAT_MESSAGE_FROM_SYSTEM|
189 FORMAT_MESSAGE_IGNORE_INSERTS,
191 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
192 (LPTSTR) &lpMsgBuf,0,NULL);
194 //gdcmErrorMacro("FindNextFile error. Error is " << (char *)lpMsgBuf
195 // <<" for the directory : "<<dirName);
200 // Real POSIX implementation: scandir is a BSD extension only, and doesn't
201 // work on debian for example
203 DIR* dir = opendir( dirName.c_str() );
209 // According to POSIX, the dirent structure contains a field char d_name[]
210 // of unspecified size, with at most NAME_MAX characters preceeding the
211 // terminating null character. Use of other fields will harm the porta-
212 // bility of your programs.
216 for (d = readdir(dir); d; d = readdir(dir))
218 fileName = dirName + d->d_name;
219 std::string temp = fileName;
220 if( stat(fileName.c_str(), &buf) != 0 )
222 //gdcmErrorMacro( strerror(errno) );
224 if ( S_ISREG(buf.st_mode) ) //is it a regular file?
226 if ( d->d_name[0]!='.')
230 std::string::size_type spacePosition = temp.find_first_of(' ');
231 if (spacePosition != std::string::npos)
233 std::cout << "=========================================== File name : [" <<temp <<
234 "] contains space(s); Discarted !" << std::endl;
235 temp.insert(spacePosition, "\\");
236 continue; /// \TODO : fix the trouble (vtk?)
237 } // if spacePosition
240 if (bbGetInputType()==0)
242 Filenames.push_back(temp);
246 } else if ( S_ISDIR(buf.st_mode) ) { //directory?
247 if ( (d->d_name[0]!='.') && recursive ) //we also skip hidden files
249 if (bbGetInputType()==1)
251 Filenames.push_back(fileName);
253 } // Type All_directories
255 tmpNumberOfFiles = Explore( fileName, recursive, recursiveLevel-1);
256 if ((bbGetInputType()==2)&&tmpNumberOfFiles==0)
258 Filenames.push_back(fileName);
260 } // Type Lsast_directories
261 numberOfFiles = numberOfFiles+tmpNumberOfFiles;
262 }// d_name && recursive
263 if ( (d->d_name[0]!='.') && !recursive ) { //we also skip hidden files
264 if ((bbGetInputType()==1) || (bbGetInputType()==2))
266 Filenames.push_back(fileName);
268 } // Type All_directories
270 }// d_name && !recursive
273 //gdcmErrorMacro( "Unexpected error" );
277 if( closedir(dir) != 0 )
279 //gdcmErrorMacro( strerror(errno) );
283 } // if recursiveLevel
285 return numberOfFiles;
289 //------------------------------------------------------------------------------
290 void FilesFromDirectory::CleanFilenames( std::string basePath )
292 std::string tmpString;
293 int i,ii,sizeFilenames = Filenames.size();
294 int j,sizeFileEnd = bbGetInputFileEnd().size();
298 //Selecting just the files in the FileEnd List
299 if (bbGetInputFileEnd().size()!=0)
301 for (i=sizeFilenames-1; i>=0; i--)
304 for (j=0; j<sizeFileEnd; j++)
306 std::string tmp=Filenames[i].substr( (Filenames[i].length()) - (bbGetInputFileEnd()[j]).length() ) ;
307 if (bbGetInputFileEnd()[j].compare( tmp )==0 )
313 if (okEraseElement==0)
315 Filenames.erase( Filenames.begin()+i );
320 sizeFilenames = Filenames.size();
322 // Cleanning paths with spaces
323 for (i=0; i<sizeFilenames; i++)
325 tmpString=Filenames[i];
327 std::string::size_type spacePosition = tmpString.find_first_of(' ');
328 if (spacePosition != std::string::npos)
330 std::cout << "=========================================== File name : [" <<tmpString <<
331 "] contains space(s); Discarted !" << std::endl;
332 tmpString.insert(spacePosition, "\\");
333 Filenames[i]=tmpString;
334 // continue; /// \TODO : fix the trouble (vtk?)
335 } // if spacePosition
339 // Alphabetical order
340 for (i=0; i<sizeFilenames; i++)
342 for (ii=i; ii<sizeFilenames; ii++)
344 if (Filenames[i]>Filenames[ii])
346 tmpString=Filenames[i];
347 Filenames[i]=Filenames[ii];
348 Filenames[ii]=tmpString;
353 // Creating SimpleFilenames
354 unsigned int lenghtBasePath = basePath.length();
355 for (i=0; i<sizeFilenames; i++)
357 SimpleFilenames.push_back( Filenames[i].substr( lenghtBasePath ) );
367 int FilesFromDirectory::Explore(std::string const &dirpath, bool recursive)
370 int numberOfFiles = 0;
371 std::string fileName;
372 std::string dirName = NormalizePath(dirpath);
374 WIN32_FIND_DATA fileData;
375 //assert( dirName[dirName.size()-1] == '' );
376 HANDLE hFile = FindFirstFile((dirName+"*").c_str(), &fileData);
378 for(BOOL b = (hFile != INVALID_HANDLE_VALUE); b;
379 b = FindNextFile(hFile, &fileData))
381 fileName = fileData.cFileName;
382 if ( fileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
384 // Need to check for . and .. to avoid infinite loop
385 if ( fileName != "." && fileName != ".." && recursive )
387 numberOfFiles += Explore(dirName+fileName, recursive);
392 // std::string temp = "\"" +dirName+fileName + "\"";
393 std::string temp = dirName+fileName;
394 std::string::size_type spacePosition = temp.find_first_of(' ');
395 if (spacePosition != std::string::npos)
397 std::cout << "=========================================== File name : [" <<temp <<
398 "] contains space(s); Discarted !" << std::endl;
399 temp.insert(spacePosition, "\\");
400 continue; /// \TODO : fix the trouble (vtk?)
402 Filenames.push_back(temp);
406 DWORD dwError = GetLastError();
407 if (hFile != INVALID_HANDLE_VALUE)
409 if (dwError != ERROR_NO_MORE_FILES)
412 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|
413 FORMAT_MESSAGE_FROM_SYSTEM|
414 FORMAT_MESSAGE_IGNORE_INSERTS,
416 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
417 (LPTSTR) &lpMsgBuf,0,NULL);
419 //gdcmErrorMacro("FindNextFile error. Error is " << (char *)lpMsgBuf
420 // <<" for the directory : "<<dirName);
425 // Real POSIX implementation: scandir is a BSD extension only, and doesn't
426 // work on debian for example
428 DIR* dir = opendir(dirName.c_str());
434 // According to POSIX, the dirent structure contains a field char d_name[]
435 // of unspecified size, with at most NAME_MAX characters preceeding the
436 // terminating null character. Use of other fields will harm the porta-
437 // bility of your programs.
441 for (d = readdir(dir); d; d = readdir(dir))
443 fileName = dirName + d->d_name;
444 std::string temp = fileName;
445 if( stat(fileName.c_str(), &buf) != 0 )
447 //gdcmErrorMacro( strerror(errno) );
449 if ( S_ISREG(buf.st_mode) ) //is it a regular file?
451 if ( d->d_name[0]!='.')
454 std::string::size_type spacePosition = temp.find_first_of(' ');
455 if (spacePosition != std::string::npos)
457 std::cout << "=========================================== File name : [" <<temp <<
458 "] contains space(s); Discarted !" << std::endl;
459 temp.insert(spacePosition, "\\");
460 continue; /// \TODO : fix the trouble (vtk?)
462 Filenames.push_back(temp);
466 else if ( S_ISDIR(buf.st_mode) ) //directory?
468 if ( d->d_name[0] != '.' && recursive ) //we also skip hidden files
470 numberOfFiles += Explore( fileName, recursive);
475 //gdcmErrorMacro( "Unexpected error" );
479 if( closedir(dir) != 0 )
481 //gdcmErrorMacro( strerror(errno) );
485 std::string tmpString;
486 int i,ii,sizeFilenames = Filenames.size();
487 for (i=0; i<sizeFilenames; i++)
489 for (ii=i; ii<sizeFilenames; ii++)
491 if (Filenames[i]>Filenames[ii])
493 tmpString=Filenames[i];
494 Filenames[i]=Filenames[ii];
495 Filenames[ii]=tmpString;
500 return numberOfFiles;
505 // EO namespace bbstd