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( DirName );
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]=='/')||(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)
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 )
145 if ((bbGetInputType()==1) || (bbGetInputType()==2))
147 std::string temp = dirName+fileName;
148 Filenames.push_back(temp);
150 } // Type All_directories
151 }// fileName && !recursive
153 // std::string temp = "\"" +dirName+fileName + "\"";
154 std::string temp = dirName+fileName;
157 std::string::size_type spacePosition = temp.find_first_of(' ');
158 if (spacePosition != std::string::npos)
160 std::cout << "=========================================== File name : [" <<temp <<
161 "] contains space(s); Discarted !" << std::endl;
162 temp.insert(spacePosition, "\\");
163 continue; /// \TODO : fix the trouble (vtk?)
168 if (bbGetInputType()==0)
170 Filenames.push_back(temp);
176 DWORD dwError = GetLastError();
177 if (hFile != INVALID_HANDLE_VALUE)
181 if (dwError != ERROR_NO_MORE_FILES)
184 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|
185 FORMAT_MESSAGE_FROM_SYSTEM|
186 FORMAT_MESSAGE_IGNORE_INSERTS,
188 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
189 (LPTSTR) &lpMsgBuf,0,NULL);
191 //gdcmErrorMacro("FindNextFile error. Error is " << (char *)lpMsgBuf
192 // <<" for the directory : "<<dirName);
197 // Real POSIX implementation: scandir is a BSD extension only, and doesn't
198 // work on debian for example
200 DIR* dir = opendir( dirName.c_str() );
206 // According to POSIX, the dirent structure contains a field char d_name[]
207 // of unspecified size, with at most NAME_MAX characters preceeding the
208 // terminating null character. Use of other fields will harm the porta-
209 // bility of your programs.
213 for (d = readdir(dir); d; d = readdir(dir))
215 fileName = dirName + d->d_name;
216 std::string temp = fileName;
217 if( stat(fileName.c_str(), &buf) != 0 )
219 //gdcmErrorMacro( strerror(errno) );
221 if ( S_ISREG(buf.st_mode) ) //is it a regular file?
223 if ( d->d_name[0]!='.')
227 std::string::size_type spacePosition = temp.find_first_of(' ');
228 if (spacePosition != std::string::npos)
230 std::cout << "=========================================== File name : [" <<temp <<
231 "] contains space(s); Discarted !" << std::endl;
232 temp.insert(spacePosition, "\\");
233 continue; /// \TODO : fix the trouble (vtk?)
234 } // if spacePosition
237 if (bbGetInputType()==0)
239 Filenames.push_back(temp);
243 } else if ( S_ISDIR(buf.st_mode) ) { //directory?
244 if ( (d->d_name[0]!='.') && recursive ) //we also skip hidden files
246 if (bbGetInputType()==1)
248 Filenames.push_back(fileName);
250 } // Type All_directories
252 tmpNumberOfFiles = Explore( fileName, recursive);
253 if ((bbGetInputType()==2)&&tmpNumberOfFiles==0)
255 Filenames.push_back(fileName);
257 } // Type Lsast_directories
258 numberOfFiles = numberOfFiles+tmpNumberOfFiles;
259 }// d_name && recursive
260 if ( (d->d_name[0]!='.') && !recursive ) { //we also skip hidden files
261 if ((bbGetInputType()==1) || (bbGetInputType()==2))
263 Filenames.push_back(fileName);
265 } // Type All_directories
267 }// d_name && !recursive
270 //gdcmErrorMacro( "Unexpected error" );
274 if( closedir(dir) != 0 )
276 //gdcmErrorMacro( strerror(errno) );
281 return numberOfFiles;
285 //------------------------------------------------------------------------------
286 void FilesFromDirectory::CleanFilenames( std::string basePath )
288 std::string tmpString;
289 int i,ii,sizeFilenames = Filenames.size();
290 int j,sizeFileEnd = bbGetInputFileEnd().size();
294 //Selecting just the files in the FileEnd List
295 if (bbGetInputFileEnd().size()!=0)
297 for (i=sizeFilenames-1; i>=0; i--)
300 for (j=0; j<sizeFileEnd; j++)
302 std::string tmp=Filenames[i].substr( (Filenames[i].length()) - (bbGetInputFileEnd()[j]).length() ) ;
303 if (bbGetInputFileEnd()[j].compare( tmp )==0 )
309 if (okEraseElement==0)
311 Filenames.erase( Filenames.begin()+i );
316 sizeFilenames = Filenames.size();
318 // Cleanning paths with spaces
319 for (i=0; i<sizeFilenames; i++)
321 tmpString=Filenames[i];
323 std::string::size_type spacePosition = tmpString.find_first_of(' ');
324 if (spacePosition != std::string::npos)
326 std::cout << "=========================================== File name : [" <<tmpString <<
327 "] contains space(s); Discarted !" << std::endl;
328 tmpString.insert(spacePosition, "\\");
329 Filenames[i]=tmpString;
330 // continue; /// \TODO : fix the trouble (vtk?)
331 } // if spacePosition
335 // Alphabetical order
336 for (i=0; i<sizeFilenames; i++)
338 for (ii=i; ii<sizeFilenames; ii++)
340 if (Filenames[i]>Filenames[ii])
342 tmpString=Filenames[i];
343 Filenames[i]=Filenames[ii];
344 Filenames[ii]=tmpString;
349 // Creating SimpleFilenames
350 unsigned int lenghtBasePath = basePath.length();
351 for (i=0; i<sizeFilenames; i++)
353 SimpleFilenames.push_back( Filenames[i].substr( lenghtBasePath ) );
363 int FilesFromDirectory::Explore(std::string const &dirpath, bool recursive)
366 int numberOfFiles = 0;
367 std::string fileName;
368 std::string dirName = NormalizePath(dirpath);
370 WIN32_FIND_DATA fileData;
371 //assert( dirName[dirName.size()-1] == '' );
372 HANDLE hFile = FindFirstFile((dirName+"*").c_str(), &fileData);
374 for(BOOL b = (hFile != INVALID_HANDLE_VALUE); b;
375 b = FindNextFile(hFile, &fileData))
377 fileName = fileData.cFileName;
378 if ( fileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
380 // Need to check for . and .. to avoid infinite loop
381 if ( fileName != "." && fileName != ".." && recursive )
383 numberOfFiles += Explore(dirName+fileName, recursive);
388 // std::string temp = "\"" +dirName+fileName + "\"";
389 std::string temp = dirName+fileName;
390 std::string::size_type spacePosition = temp.find_first_of(' ');
391 if (spacePosition != std::string::npos)
393 std::cout << "=========================================== File name : [" <<temp <<
394 "] contains space(s); Discarted !" << std::endl;
395 temp.insert(spacePosition, "\\");
396 continue; /// \TODO : fix the trouble (vtk?)
398 Filenames.push_back(temp);
402 DWORD dwError = GetLastError();
403 if (hFile != INVALID_HANDLE_VALUE)
405 if (dwError != ERROR_NO_MORE_FILES)
408 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|
409 FORMAT_MESSAGE_FROM_SYSTEM|
410 FORMAT_MESSAGE_IGNORE_INSERTS,
412 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
413 (LPTSTR) &lpMsgBuf,0,NULL);
415 //gdcmErrorMacro("FindNextFile error. Error is " << (char *)lpMsgBuf
416 // <<" for the directory : "<<dirName);
421 // Real POSIX implementation: scandir is a BSD extension only, and doesn't
422 // work on debian for example
424 DIR* dir = opendir(dirName.c_str());
430 // According to POSIX, the dirent structure contains a field char d_name[]
431 // of unspecified size, with at most NAME_MAX characters preceeding the
432 // terminating null character. Use of other fields will harm the porta-
433 // bility of your programs.
437 for (d = readdir(dir); d; d = readdir(dir))
439 fileName = dirName + d->d_name;
440 std::string temp = fileName;
441 if( stat(fileName.c_str(), &buf) != 0 )
443 //gdcmErrorMacro( strerror(errno) );
445 if ( S_ISREG(buf.st_mode) ) //is it a regular file?
447 if ( d->d_name[0]!='.')
450 std::string::size_type spacePosition = temp.find_first_of(' ');
451 if (spacePosition != std::string::npos)
453 std::cout << "=========================================== File name : [" <<temp <<
454 "] contains space(s); Discarted !" << std::endl;
455 temp.insert(spacePosition, "\\");
456 continue; /// \TODO : fix the trouble (vtk?)
458 Filenames.push_back(temp);
462 else if ( S_ISDIR(buf.st_mode) ) //directory?
464 if ( d->d_name[0] != '.' && recursive ) //we also skip hidden files
466 numberOfFiles += Explore( fileName, recursive);
471 //gdcmErrorMacro( "Unexpected error" );
475 if( closedir(dir) != 0 )
477 //gdcmErrorMacro( strerror(errno) );
481 std::string tmpString;
482 int i,ii,sizeFilenames = Filenames.size();
483 for (i=0; i<sizeFilenames; i++)
485 for (ii=i; ii<sizeFilenames; ii++)
487 if (Filenames[i]>Filenames[ii])
489 tmpString=Filenames[i];
490 Filenames[i]=Filenames[ii];
491 Filenames[ii]=tmpString;
496 return numberOfFiles;
501 // EO namespace bbstd