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()
50 printf("EED FilesFromDirectory::Process Start\n");
53 SimpleFilenames.clear();
54 DirName = bbGetInputIn();
55 bool rec = bbGetInputRecursive();
56 /*int nbFiles = */ Explore(DirName, rec);
57 CleanFilenames( bbGetInputIn() );
58 bbSetOutputOut(Filenames);
59 bbSetOutputOutSimple(SimpleFilenames);
61 printf("EED FilesFromDirectory::Process End\n");
64 void FilesFromDirectory::bbUserSetDefaultValues()
67 bbSetInputRecursive(false);
71 void FilesFromDirectory::bbUserInitializeProcessing()
75 void FilesFromDirectory::bbUserFinalizeProcessing()
80 * \brief Add a SEPARATOR to the end of the name if necessary
81 * @param pathname file/directory name to normalize
83 std::string FilesFromDirectory::NormalizePath(std::string const &pathname)
86 const char FILESEPARATOR = '\\';
88 const char FILESEPARATOR = '/';
91 std::string name = pathname;
92 int size = name.size();
94 if ( name[size-1] != FILESEPARATOR )
96 name += FILESEPARATOR;
102 * \brief Explores a directory with possibility of recursion
103 * return number of files read
104 * @param dirpath directory to explore
105 * @param recursive whether we want recursion or not
110 int FilesFromDirectory::Explore(std::string const &dirpath, bool recursive)
112 int numberOfFiles = 0;
113 std::string dirName = NormalizePath(dirpath);
114 int tmpNumberOfFiles;
115 std::string fileName;
117 WIN32_FIND_DATA fileData;
118 //assert( dirName[dirName.size()-1] == '' );
119 HANDLE hFile = FindFirstFile((dirName+"*").c_str(), &fileData);
121 for(BOOL b = (hFile != INVALID_HANDLE_VALUE); b;
122 b = FindNextFile(hFile, &fileData))
124 fileName = fileData.cFileName;
125 if ( fileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
127 // Need to check for . and .. to avoid infinite loop
128 if ( fileName != "." && fileName != ".." && recursive )
130 if (bbGetInputType()==1)
132 std::string temp = dirName+fileName;
133 Filenames.push_back(temp);
135 } // Type ALL_directories
137 tmpNumberOfFiles = Explore(dirName+fileName, recursive);
138 if ((bbGetInputType()==2)&&tmpNumberOfFiles==0)
140 std::string temp = dirName+fileName;
141 Filenames.push_back(temp);
143 } // Type Lsast_directories
145 numberOfFiles = numberOfFiles + tmpNumberOfFiles;
148 // std::string temp = "\"" +dirName+fileName + "\"";
149 std::string temp = dirName+fileName;
152 std::string::size_type spacePosition = temp.find_first_of(' ');
153 if (spacePosition != std::string::npos)
155 std::cout << "=========================================== File name : [" <<temp <<
156 "] contains space(s); Discarted !" << std::endl;
157 temp.insert(spacePosition, "\\");
158 continue; /// \TODO : fix the trouble (vtk?)
163 if (bbGetInputType()==0)
165 Filenames.push_back(temp);
171 DWORD dwError = GetLastError();
172 if (hFile != INVALID_HANDLE_VALUE)
176 if (dwError != ERROR_NO_MORE_FILES)
179 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|
180 FORMAT_MESSAGE_FROM_SYSTEM|
181 FORMAT_MESSAGE_IGNORE_INSERTS,
183 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
184 (LPTSTR) &lpMsgBuf,0,NULL);
186 //gdcmErrorMacro("FindNextFile error. Error is " << (char *)lpMsgBuf
187 // <<" for the directory : "<<dirName);
192 // Real POSIX implementation: scandir is a BSD extension only, and doesn't
193 // work on debian for example
195 DIR* dir = opendir( dirName.c_str() );
201 // According to POSIX, the dirent structure contains a field char d_name[]
202 // of unspecified size, with at most NAME_MAX characters preceeding the
203 // terminating null character. Use of other fields will harm the porta-
204 // bility of your programs.
208 for (d = readdir(dir); d; d = readdir(dir))
210 fileName = dirName + d->d_name;
211 std::string temp = fileName;
212 if( stat(fileName.c_str(), &buf) != 0 )
214 //gdcmErrorMacro( strerror(errno) );
216 if ( S_ISREG(buf.st_mode) ) //is it a regular file?
218 if ( d->d_name[0]!='.')
222 std::string::size_type spacePosition = temp.find_first_of(' ');
223 if (spacePosition != std::string::npos)
225 std::cout << "=========================================== File name : [" <<temp <<
226 "] contains space(s); Discarted !" << std::endl;
227 temp.insert(spacePosition, "\\");
228 continue; /// \TODO : fix the trouble (vtk?)
229 } // if spacePosition
232 if (bbGetInputType()==0)
234 Filenames.push_back(temp);
238 } else if ( S_ISDIR(buf.st_mode) ) { //directory?
239 if ( d->d_name[0] != '.' && recursive ) //we also skip hidden files
241 if (bbGetInputType()==1)
243 Filenames.push_back(fileName);
245 } // Type All_directories
247 tmpNumberOfFiles = Explore( fileName, recursive);
248 if ((bbGetInputType()==2)&&tmpNumberOfFiles==0)
250 Filenames.push_back(fileName);
252 } // Type Lsast_directories
253 numberOfFiles = numberOfFiles+tmpNumberOfFiles;
256 //gdcmErrorMacro( "Unexpected error" );
260 if( closedir(dir) != 0 )
262 //gdcmErrorMacro( strerror(errno) );
267 return numberOfFiles;
271 //------------------------------------------------------------------------------
272 void FilesFromDirectory::CleanFilenames( std::string basePath )
274 std::string tmpString;
275 int i,ii,sizeFilenames = Filenames.size();
276 int j,sizeFileEnd = bbGetInputFileEnd().size();
280 //Selecting just the files in the FileEnd List
281 if (bbGetInputFileEnd().size()!=0)
283 for (i=sizeFilenames-1; i>=0; i--)
286 for (j=0; j<sizeFileEnd; j++)
288 std::string tmp=Filenames[i].substr( (Filenames[i].length()) - (bbGetInputFileEnd()[j]).length() ) ;
289 if (bbGetInputFileEnd()[j].compare( tmp )==0 )
295 if (okEraseElement==0)
297 Filenames.erase( Filenames.begin()+i );
302 sizeFilenames = Filenames.size();
304 // Cleanning paths with spaces
305 for (i=0; i<sizeFilenames; i++)
307 tmpString=Filenames[i];
309 std::string::size_type spacePosition = tmpString.find_first_of(' ');
310 if (spacePosition != std::string::npos)
312 std::cout << "=========================================== File name : [" <<tmpString <<
313 "] contains space(s); Discarted !" << std::endl;
314 tmpString.insert(spacePosition, "\\");
315 Filenames[i]=tmpString;
316 // continue; /// \TODO : fix the trouble (vtk?)
317 } // if spacePosition
321 // Alphabetical order
322 for (i=0; i<sizeFilenames; i++)
324 for (ii=i; ii<sizeFilenames; ii++)
326 if (Filenames[i]>Filenames[ii])
328 tmpString=Filenames[i];
329 Filenames[i]=Filenames[ii];
330 Filenames[ii]=tmpString;
335 // Creating SimpleFilenames
336 unsigned int lenghtBasePath = basePath.length();
337 for (i=0; i<sizeFilenames; i++)
339 SimpleFilenames.push_back( Filenames[i].substr( lenghtBasePath ) );
349 int FilesFromDirectory::Explore(std::string const &dirpath, bool recursive)
352 int numberOfFiles = 0;
353 std::string fileName;
354 std::string dirName = NormalizePath(dirpath);
356 WIN32_FIND_DATA fileData;
357 //assert( dirName[dirName.size()-1] == '' );
358 HANDLE hFile = FindFirstFile((dirName+"*").c_str(), &fileData);
360 for(BOOL b = (hFile != INVALID_HANDLE_VALUE); b;
361 b = FindNextFile(hFile, &fileData))
363 fileName = fileData.cFileName;
364 if ( fileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
366 // Need to check for . and .. to avoid infinite loop
367 if ( fileName != "." && fileName != ".." && recursive )
369 numberOfFiles += Explore(dirName+fileName, recursive);
374 // std::string temp = "\"" +dirName+fileName + "\"";
375 std::string temp = dirName+fileName;
376 std::string::size_type spacePosition = temp.find_first_of(' ');
377 if (spacePosition != std::string::npos)
379 std::cout << "=========================================== File name : [" <<temp <<
380 "] contains space(s); Discarted !" << std::endl;
381 temp.insert(spacePosition, "\\");
382 continue; /// \TODO : fix the trouble (vtk?)
384 Filenames.push_back(temp);
388 DWORD dwError = GetLastError();
389 if (hFile != INVALID_HANDLE_VALUE)
391 if (dwError != ERROR_NO_MORE_FILES)
394 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|
395 FORMAT_MESSAGE_FROM_SYSTEM|
396 FORMAT_MESSAGE_IGNORE_INSERTS,
398 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
399 (LPTSTR) &lpMsgBuf,0,NULL);
401 //gdcmErrorMacro("FindNextFile error. Error is " << (char *)lpMsgBuf
402 // <<" for the directory : "<<dirName);
407 // Real POSIX implementation: scandir is a BSD extension only, and doesn't
408 // work on debian for example
410 DIR* dir = opendir(dirName.c_str());
416 // According to POSIX, the dirent structure contains a field char d_name[]
417 // of unspecified size, with at most NAME_MAX characters preceeding the
418 // terminating null character. Use of other fields will harm the porta-
419 // bility of your programs.
423 for (d = readdir(dir); d; d = readdir(dir))
425 fileName = dirName + d->d_name;
426 std::string temp = fileName;
427 if( stat(fileName.c_str(), &buf) != 0 )
429 //gdcmErrorMacro( strerror(errno) );
431 if ( S_ISREG(buf.st_mode) ) //is it a regular file?
433 if ( d->d_name[0]!='.')
436 std::string::size_type spacePosition = temp.find_first_of(' ');
437 if (spacePosition != std::string::npos)
439 std::cout << "=========================================== File name : [" <<temp <<
440 "] contains space(s); Discarted !" << std::endl;
441 temp.insert(spacePosition, "\\");
442 continue; /// \TODO : fix the trouble (vtk?)
444 Filenames.push_back(temp);
448 else if ( S_ISDIR(buf.st_mode) ) //directory?
450 if ( d->d_name[0] != '.' && recursive ) //we also skip hidden files
452 numberOfFiles += Explore( fileName, recursive);
457 //gdcmErrorMacro( "Unexpected error" );
461 if( closedir(dir) != 0 )
463 //gdcmErrorMacro( strerror(errno) );
467 std::string tmpString;
468 int i,ii,sizeFilenames = Filenames.size();
469 for (i=0; i<sizeFilenames; i++)
471 for (ii=i; ii<sizeFilenames; ii++)
473 if (Filenames[i]>Filenames[ii])
475 tmpString=Filenames[i];
476 Filenames[i]=Filenames[ii];
477 Filenames[ii]=tmpString;
482 return numberOfFiles;
487 // EO namespace bbstd