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();
53 if (bbGetInputActive()==true)
55 if (bbGetInputIn()!="")
57 DirName = bbGetInputIn();
58 /*int nbFiles = */ Explore(DirName, bbGetInputRecursive(), bbGetInputRecursiveLevel() );
59 CleanFilenames( DirName );
62 bbSetOutputOut(Filenames);
63 bbSetOutputOutSimple(SimpleFilenames);
66 void FilesFromDirectory::bbUserSetDefaultValues()
68 bbSetInputActive(true);
70 bbSetInputRecursive(false);
72 bbSetInputRecursiveLevel(999);
75 void FilesFromDirectory::bbUserInitializeProcessing()
79 void FilesFromDirectory::bbUserFinalizeProcessing()
84 * \brief Add a SEPARATOR to the end of the name if necessary
85 * @param pathname file/directory name to normalize
87 std::string FilesFromDirectory::NormalizePath(std::string const &pathname)
90 const char FILESEPARATOR = '\\';
92 const char FILESEPARATOR = '/';
95 std::string name = pathname;
96 int size = name.size();
98 if (!((name[size-1]=='/')||(name[size-1]=='\\')))
100 name += FILESEPARATOR;
106 * \brief Explores a directory with possibility of recursion
107 * return number of files read
108 * @param dirpath directory to explore
109 * @param recursive whether we want recursion or not
114 int FilesFromDirectory::Explore(std::string const &dirpath, bool recursive, int recursiveLevel)
116 int numberOfFiles = 0;
118 if (recursiveLevel>=0){
120 std::string dirName = NormalizePath(dirpath);
121 int tmpNumberOfFiles;
122 std::string fileName;
124 WIN32_FIND_DATA fileData;
125 //assert( dirName[dirName.size()-1] == '' );
126 HANDLE hFile = FindFirstFile((dirName+"*").c_str(), &fileData);
128 for(BOOL b = (hFile != INVALID_HANDLE_VALUE); b;
129 b = FindNextFile(hFile, &fileData))
131 fileName = fileData.cFileName;
132 if ( fileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
134 // Need to check for . and .. to avoid infinite loop
135 if ( fileName != "." && fileName != ".." && recursive )
137 if (bbGetInputType()==1)
139 std::string temp = dirName+fileName;
140 Filenames.push_back(temp);
142 } // Type ALL_directories
144 tmpNumberOfFiles = Explore(dirName+fileName, recursive,recursiveLevel-1);
145 if ((bbGetInputType()==2)&&tmpNumberOfFiles==0)
147 std::string temp = dirName+fileName;
148 Filenames.push_back(temp);
150 } // Type Lsast_directories
152 numberOfFiles = numberOfFiles + tmpNumberOfFiles;
154 if ( fileName != "." && fileName != ".." && !recursive )
156 if ((bbGetInputType()==1) || (bbGetInputType()==2))
158 std::string temp = dirName+fileName;
159 Filenames.push_back(temp);
161 } // Type All_directories
162 }// fileName && !recursive
164 // std::string temp = "\"" +dirName+fileName + "\"";
165 std::string temp = dirName+fileName;
168 std::string::size_type spacePosition = temp.find_first_of(' ');
169 if (spacePosition != std::string::npos)
171 std::cout << "=========================================== File name : [" <<temp <<
172 "] contains space(s); Discarted !" << std::endl;
173 temp.insert(spacePosition, "\\");
174 continue; /// \TODO : fix the trouble (vtk?)
179 if (bbGetInputType()==0)
181 Filenames.push_back(temp);
187 DWORD dwError = GetLastError();
188 if (hFile != INVALID_HANDLE_VALUE)
192 if (dwError != ERROR_NO_MORE_FILES)
195 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|
196 FORMAT_MESSAGE_FROM_SYSTEM|
197 FORMAT_MESSAGE_IGNORE_INSERTS,
199 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
200 (LPTSTR) &lpMsgBuf,0,NULL);
202 //gdcmErrorMacro("FindNextFile error. Error is " << (char *)lpMsgBuf
203 // <<" for the directory : "<<dirName);
208 // Real POSIX implementation: scandir is a BSD extension only, and doesn't
209 // work on debian for example
211 DIR* dir = opendir( dirName.c_str() );
217 // According to POSIX, the dirent structure contains a field char d_name[]
218 // of unspecified size, with at most NAME_MAX characters preceeding the
219 // terminating null character. Use of other fields will harm the porta-
220 // bility of your programs.
224 for (d = readdir(dir); d; d = readdir(dir))
226 fileName = dirName + d->d_name;
227 std::string temp = fileName;
228 if( stat(fileName.c_str(), &buf) != 0 )
230 //gdcmErrorMacro( strerror(errno) );
232 if ( S_ISREG(buf.st_mode) ) //is it a regular file?
234 if ( d->d_name[0]!='.')
238 std::string::size_type spacePosition = temp.find_first_of(' ');
239 if (spacePosition != std::string::npos)
241 std::cout << "=========================================== File name : [" <<temp <<
242 "] contains space(s); Discarted !" << std::endl;
243 temp.insert(spacePosition, "\\");
244 continue; /// \TODO : fix the trouble (vtk?)
245 } // if spacePosition
248 if (bbGetInputType()==0)
250 Filenames.push_back(temp);
254 } else if ( S_ISDIR(buf.st_mode) ) { //directory?
255 if ( (d->d_name[0]!='.') && recursive ) //we also skip hidden files
257 if (bbGetInputType()==1)
259 Filenames.push_back(fileName);
261 } // Type All_directories
263 tmpNumberOfFiles = Explore( fileName, recursive, recursiveLevel-1);
264 if ((bbGetInputType()==2)&&tmpNumberOfFiles==0)
266 Filenames.push_back(fileName);
268 } // Type Lsast_directories
269 numberOfFiles = numberOfFiles+tmpNumberOfFiles;
270 }// d_name && recursive
271 if ( (d->d_name[0]!='.') && !recursive ) { //we also skip hidden files
272 if ((bbGetInputType()==1) || (bbGetInputType()==2))
274 Filenames.push_back(fileName);
276 } // Type All_directories
278 }// d_name && !recursive
281 //gdcmErrorMacro( "Unexpected error" );
285 if( closedir(dir) != 0 )
287 //gdcmErrorMacro( strerror(errno) );
291 } // if recursiveLevel
293 return numberOfFiles;
297 //------------------------------------------------------------------------------
298 void FilesFromDirectory::CleanFilenames( std::string basePath )
300 std::string tmpString;
301 int i,ii,sizeFilenames = Filenames.size();
302 int j,sizeFileEnd = bbGetInputFileEnd().size();
305 //Selecting just the files in the FileEnd List
306 if (bbGetInputFileEnd().size()!=0)
308 for (i=sizeFilenames-1; i>=0; i--)
311 for (j=0; j<sizeFileEnd; j++)
313 posStr=(Filenames[i].length()) - (bbGetInputFileEnd()[j]).length();
316 std::string tmp=Filenames[i].substr( posStr ) ;
317 if (bbGetInputFileEnd()[j].compare( tmp )==0 )
324 if (okEraseElement==0)
326 Filenames.erase( Filenames.begin()+i );
330 sizeFilenames = Filenames.size();
331 // Cleanning paths with spaces
332 for (i=0; i<sizeFilenames; i++)
334 tmpString=Filenames[i];
335 std::string::size_type spacePosition = tmpString.find_first_of(' ');
336 if (spacePosition != std::string::npos)
338 std::cout << "=========================================== File name : [" <<tmpString <<
339 "] contains space(s); Discarted !" << std::endl;
340 tmpString.insert(spacePosition, "\\");
341 Filenames[i]=tmpString;
342 // continue; /// \TODO : fix the trouble (vtk?)
343 } // if spacePosition
346 // Alphabetical order
347 for (i=0; i<sizeFilenames; i++)
349 for (ii=i; ii<sizeFilenames; ii++)
351 if (Filenames[i]>Filenames[ii])
353 tmpString=Filenames[i];
354 Filenames[i]=Filenames[ii];
355 Filenames[ii]=tmpString;
359 // Creating SimpleFilenames
360 unsigned int lenghtBasePath = basePath.length();
361 for (i=0; i<sizeFilenames; i++)
363 SimpleFilenames.push_back( Filenames[i].substr( lenghtBasePath ) );
372 int FilesFromDirectory::Explore(std::string const &dirpath, bool recursive)
375 int numberOfFiles = 0;
376 std::string fileName;
377 std::string dirName = NormalizePath(dirpath);
379 WIN32_FIND_DATA fileData;
380 //assert( dirName[dirName.size()-1] == '' );
381 HANDLE hFile = FindFirstFile((dirName+"*").c_str(), &fileData);
383 for(BOOL b = (hFile != INVALID_HANDLE_VALUE); b;
384 b = FindNextFile(hFile, &fileData))
386 fileName = fileData.cFileName;
387 if ( fileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
389 // Need to check for . and .. to avoid infinite loop
390 if ( fileName != "." && fileName != ".." && recursive )
392 numberOfFiles += Explore(dirName+fileName, recursive);
397 // std::string temp = "\"" +dirName+fileName + "\"";
398 std::string temp = dirName+fileName;
399 std::string::size_type spacePosition = temp.find_first_of(' ');
400 if (spacePosition != std::string::npos)
402 std::cout << "=========================================== File name : [" <<temp <<
403 "] contains space(s); Discarted !" << std::endl;
404 temp.insert(spacePosition, "\\");
405 continue; /// \TODO : fix the trouble (vtk?)
407 Filenames.push_back(temp);
411 DWORD dwError = GetLastError();
412 if (hFile != INVALID_HANDLE_VALUE)
414 if (dwError != ERROR_NO_MORE_FILES)
417 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|
418 FORMAT_MESSAGE_FROM_SYSTEM|
419 FORMAT_MESSAGE_IGNORE_INSERTS,
421 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
422 (LPTSTR) &lpMsgBuf,0,NULL);
424 //gdcmErrorMacro("FindNextFile error. Error is " << (char *)lpMsgBuf
425 // <<" for the directory : "<<dirName);
430 // Real POSIX implementation: scandir is a BSD extension only, and doesn't
431 // work on debian for example
433 DIR* dir = opendir(dirName.c_str());
439 // According to POSIX, the dirent structure contains a field char d_name[]
440 // of unspecified size, with at most NAME_MAX characters preceeding the
441 // terminating null character. Use of other fields will harm the porta-
442 // bility of your programs.
446 for (d = readdir(dir); d; d = readdir(dir))
448 fileName = dirName + d->d_name;
449 std::string temp = fileName;
450 if( stat(fileName.c_str(), &buf) != 0 )
452 //gdcmErrorMacro( strerror(errno) );
454 if ( S_ISREG(buf.st_mode) ) //is it a regular file?
456 if ( d->d_name[0]!='.')
459 std::string::size_type spacePosition = temp.find_first_of(' ');
460 if (spacePosition != std::string::npos)
462 std::cout << "=========================================== File name : [" <<temp <<
463 "] contains space(s); Discarted !" << std::endl;
464 temp.insert(spacePosition, "\\");
465 continue; /// \TODO : fix the trouble (vtk?)
467 Filenames.push_back(temp);
471 else if ( S_ISDIR(buf.st_mode) ) //directory?
473 if ( d->d_name[0] != '.' && recursive ) //we also skip hidden files
475 numberOfFiles += Explore( fileName, recursive);
480 //gdcmErrorMacro( "Unexpected error" );
484 if( closedir(dir) != 0 )
486 //gdcmErrorMacro( strerror(errno) );
490 std::string tmpString;
491 int i,ii,sizeFilenames = Filenames.size();
492 for (i=0; i<sizeFilenames; i++)
494 for (ii=i; ii<sizeFilenames; ii++)
496 if (Filenames[i]>Filenames[ii])
498 tmpString=Filenames[i];
499 Filenames[i]=Filenames[ii];
500 Filenames[ii]=tmpString;
505 return numberOfFiles;
510 // EO namespace bbstd