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 if (bbGetInputIn()!="")
54 DirName = bbGetInputIn();
55 /*int nbFiles = */ Explore(DirName, bbGetInputRecursive(), bbGetInputRecursiveLevel() );
56 CleanFilenames( DirName );
58 bbSetOutputOut(Filenames);
59 bbSetOutputOutSimple(SimpleFilenames);
62 void FilesFromDirectory::bbUserSetDefaultValues()
65 bbSetInputRecursive(false);
67 bbSetInputRecursiveLevel(999);
70 void FilesFromDirectory::bbUserInitializeProcessing()
74 void FilesFromDirectory::bbUserFinalizeProcessing()
79 * \brief Add a SEPARATOR to the end of the name if necessary
80 * @param pathname file/directory name to normalize
82 std::string FilesFromDirectory::NormalizePath(std::string const &pathname)
85 const char FILESEPARATOR = '\\';
87 const char FILESEPARATOR = '/';
90 std::string name = pathname;
91 int size = name.size();
93 if (!((name[size-1]=='/')||(name[size-1]=='\\')))
95 name += FILESEPARATOR;
101 * \brief Explores a directory with possibility of recursion
102 * return number of files read
103 * @param dirpath directory to explore
104 * @param recursive whether we want recursion or not
109 int FilesFromDirectory::Explore(std::string const &dirpath, bool recursive, int recursiveLevel)
111 int numberOfFiles = 0;
113 if (recursiveLevel>=0){
115 std::string dirName = NormalizePath(dirpath);
116 int tmpNumberOfFiles;
117 std::string fileName;
119 WIN32_FIND_DATA fileData;
120 //assert( dirName[dirName.size()-1] == '' );
121 HANDLE hFile = FindFirstFile((dirName+"*").c_str(), &fileData);
123 for(BOOL b = (hFile != INVALID_HANDLE_VALUE); b;
124 b = FindNextFile(hFile, &fileData))
126 fileName = fileData.cFileName;
127 if ( fileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
129 // Need to check for . and .. to avoid infinite loop
130 if ( fileName != "." && fileName != ".." && recursive )
132 if (bbGetInputType()==1)
134 std::string temp = dirName+fileName;
135 Filenames.push_back(temp);
137 } // Type ALL_directories
139 tmpNumberOfFiles = Explore(dirName+fileName, recursive,recursiveLevel-1);
140 if ((bbGetInputType()==2)&&tmpNumberOfFiles==0)
142 std::string temp = dirName+fileName;
143 Filenames.push_back(temp);
145 } // Type Lsast_directories
147 numberOfFiles = numberOfFiles + tmpNumberOfFiles;
149 if ( fileName != "." && fileName != ".." && !recursive )
151 if ((bbGetInputType()==1) || (bbGetInputType()==2))
153 std::string temp = dirName+fileName;
154 Filenames.push_back(temp);
156 } // Type All_directories
157 }// fileName && !recursive
159 // std::string temp = "\"" +dirName+fileName + "\"";
160 std::string temp = dirName+fileName;
163 std::string::size_type spacePosition = temp.find_first_of(' ');
164 if (spacePosition != std::string::npos)
166 std::cout << "=========================================== File name : [" <<temp <<
167 "] contains space(s); Discarted !" << std::endl;
168 temp.insert(spacePosition, "\\");
169 continue; /// \TODO : fix the trouble (vtk?)
174 if (bbGetInputType()==0)
176 Filenames.push_back(temp);
182 DWORD dwError = GetLastError();
183 if (hFile != INVALID_HANDLE_VALUE)
187 if (dwError != ERROR_NO_MORE_FILES)
190 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|
191 FORMAT_MESSAGE_FROM_SYSTEM|
192 FORMAT_MESSAGE_IGNORE_INSERTS,
194 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
195 (LPTSTR) &lpMsgBuf,0,NULL);
197 //gdcmErrorMacro("FindNextFile error. Error is " << (char *)lpMsgBuf
198 // <<" for the directory : "<<dirName);
203 // Real POSIX implementation: scandir is a BSD extension only, and doesn't
204 // work on debian for example
206 DIR* dir = opendir( dirName.c_str() );
212 // According to POSIX, the dirent structure contains a field char d_name[]
213 // of unspecified size, with at most NAME_MAX characters preceeding the
214 // terminating null character. Use of other fields will harm the porta-
215 // bility of your programs.
219 for (d = readdir(dir); d; d = readdir(dir))
221 fileName = dirName + d->d_name;
222 std::string temp = fileName;
223 if( stat(fileName.c_str(), &buf) != 0 )
225 //gdcmErrorMacro( strerror(errno) );
227 if ( S_ISREG(buf.st_mode) ) //is it a regular file?
229 if ( d->d_name[0]!='.')
233 std::string::size_type spacePosition = temp.find_first_of(' ');
234 if (spacePosition != std::string::npos)
236 std::cout << "=========================================== File name : [" <<temp <<
237 "] contains space(s); Discarted !" << std::endl;
238 temp.insert(spacePosition, "\\");
239 continue; /// \TODO : fix the trouble (vtk?)
240 } // if spacePosition
243 if (bbGetInputType()==0)
245 Filenames.push_back(temp);
249 } else if ( S_ISDIR(buf.st_mode) ) { //directory?
250 if ( (d->d_name[0]!='.') && recursive ) //we also skip hidden files
252 if (bbGetInputType()==1)
254 Filenames.push_back(fileName);
256 } // Type All_directories
258 tmpNumberOfFiles = Explore( fileName, recursive, recursiveLevel-1);
259 if ((bbGetInputType()==2)&&tmpNumberOfFiles==0)
261 Filenames.push_back(fileName);
263 } // Type Lsast_directories
264 numberOfFiles = numberOfFiles+tmpNumberOfFiles;
265 }// d_name && recursive
266 if ( (d->d_name[0]!='.') && !recursive ) { //we also skip hidden files
267 if ((bbGetInputType()==1) || (bbGetInputType()==2))
269 Filenames.push_back(fileName);
271 } // Type All_directories
273 }// d_name && !recursive
276 //gdcmErrorMacro( "Unexpected error" );
280 if( closedir(dir) != 0 )
282 //gdcmErrorMacro( strerror(errno) );
286 } // if recursiveLevel
288 return numberOfFiles;
292 //------------------------------------------------------------------------------
293 void FilesFromDirectory::CleanFilenames( std::string basePath )
295 std::string tmpString;
296 int i,ii,sizeFilenames = Filenames.size();
297 int j,sizeFileEnd = bbGetInputFileEnd().size();
300 //Selecting just the files in the FileEnd List
301 if (bbGetInputFileEnd().size()!=0)
303 for (i=sizeFilenames-1; i>=0; i--)
306 for (j=0; j<sizeFileEnd; j++)
308 posStr=(Filenames[i].length()) - (bbGetInputFileEnd()[j]).length();
311 std::string tmp=Filenames[i].substr( posStr ) ;
312 if (bbGetInputFileEnd()[j].compare( tmp )==0 )
319 if (okEraseElement==0)
321 Filenames.erase( Filenames.begin()+i );
325 sizeFilenames = Filenames.size();
326 // Cleanning paths with spaces
327 for (i=0; i<sizeFilenames; i++)
329 tmpString=Filenames[i];
330 std::string::size_type spacePosition = tmpString.find_first_of(' ');
331 if (spacePosition != std::string::npos)
333 std::cout << "=========================================== File name : [" <<tmpString <<
334 "] contains space(s); Discarted !" << std::endl;
335 tmpString.insert(spacePosition, "\\");
336 Filenames[i]=tmpString;
337 // continue; /// \TODO : fix the trouble (vtk?)
338 } // if spacePosition
341 // Alphabetical order
342 for (i=0; i<sizeFilenames; i++)
344 for (ii=i; ii<sizeFilenames; ii++)
346 if (Filenames[i]>Filenames[ii])
348 tmpString=Filenames[i];
349 Filenames[i]=Filenames[ii];
350 Filenames[ii]=tmpString;
354 // Creating SimpleFilenames
355 unsigned int lenghtBasePath = basePath.length();
356 for (i=0; i<sizeFilenames; i++)
358 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