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( bbGetInputIn() );
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] != FILESEPARATOR )
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;
144 // std::string temp = "\"" +dirName+fileName + "\"";
145 std::string temp = dirName+fileName;
148 std::string::size_type spacePosition = temp.find_first_of(' ');
149 if (spacePosition != std::string::npos)
151 std::cout << "=========================================== File name : [" <<temp <<
152 "] contains space(s); Discarted !" << std::endl;
153 temp.insert(spacePosition, "\\");
154 continue; /// \TODO : fix the trouble (vtk?)
159 if (bbGetInputType()==0)
161 Filenames.push_back(temp);
167 DWORD dwError = GetLastError();
168 if (hFile != INVALID_HANDLE_VALUE)
172 if (dwError != ERROR_NO_MORE_FILES)
175 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|
176 FORMAT_MESSAGE_FROM_SYSTEM|
177 FORMAT_MESSAGE_IGNORE_INSERTS,
179 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
180 (LPTSTR) &lpMsgBuf,0,NULL);
182 //gdcmErrorMacro("FindNextFile error. Error is " << (char *)lpMsgBuf
183 // <<" for the directory : "<<dirName);
188 // Real POSIX implementation: scandir is a BSD extension only, and doesn't
189 // work on debian for example
191 DIR* dir = opendir( dirName.c_str() );
197 // According to POSIX, the dirent structure contains a field char d_name[]
198 // of unspecified size, with at most NAME_MAX characters preceeding the
199 // terminating null character. Use of other fields will harm the porta-
200 // bility of your programs.
204 for (d = readdir(dir); d; d = readdir(dir))
206 fileName = dirName + d->d_name;
207 std::string temp = fileName;
208 if( stat(fileName.c_str(), &buf) != 0 )
210 //gdcmErrorMacro( strerror(errno) );
212 if ( S_ISREG(buf.st_mode) ) //is it a regular file?
214 if ( d->d_name[0]!='.')
218 std::string::size_type spacePosition = temp.find_first_of(' ');
219 if (spacePosition != std::string::npos)
221 std::cout << "=========================================== File name : [" <<temp <<
222 "] contains space(s); Discarted !" << std::endl;
223 temp.insert(spacePosition, "\\");
224 continue; /// \TODO : fix the trouble (vtk?)
225 } // if spacePosition
228 if (bbGetInputType()==0)
230 Filenames.push_back(temp);
234 } else if ( S_ISDIR(buf.st_mode) ) { //directory?
235 if ( d->d_name[0] != '.' && recursive ) //we also skip hidden files
237 if (bbGetInputType()==1)
239 Filenames.push_back(fileName);
241 } // Type All_directories
243 tmpNumberOfFiles = Explore( fileName, recursive);
244 if ((bbGetInputType()==2)&&tmpNumberOfFiles==0)
246 Filenames.push_back(fileName);
248 } // Type Lsast_directories
249 numberOfFiles = numberOfFiles+tmpNumberOfFiles;
252 //gdcmErrorMacro( "Unexpected error" );
256 if( closedir(dir) != 0 )
258 //gdcmErrorMacro( strerror(errno) );
263 return numberOfFiles;
267 //------------------------------------------------------------------------------
268 void FilesFromDirectory::CleanFilenames( std::string basePath )
270 std::string tmpString;
271 int i,ii,sizeFilenames = Filenames.size();
272 int j,sizeFileEnd = bbGetInputFileEnd().size();
276 //Selecting just the files in the FileEnd List
277 if (bbGetInputFileEnd().size()!=0)
279 for (i=sizeFilenames-1; i>=0; i--)
282 for (j=0; j<sizeFileEnd; j++)
284 std::string tmp=Filenames[i].substr( (Filenames[i].length()) - (bbGetInputFileEnd()[j]).length() ) ;
285 if (bbGetInputFileEnd()[j].compare( tmp )==0 )
291 if (okEraseElement==0)
293 Filenames.erase( Filenames.begin()+i );
298 sizeFilenames = Filenames.size();
300 // Cleanning paths with spaces
301 for (i=0; i<sizeFilenames; i++)
303 tmpString=Filenames[i];
305 std::string::size_type spacePosition = tmpString.find_first_of(' ');
306 if (spacePosition != std::string::npos)
308 std::cout << "=========================================== File name : [" <<tmpString <<
309 "] contains space(s); Discarted !" << std::endl;
310 tmpString.insert(spacePosition, "\\");
311 Filenames[i]=tmpString;
312 // continue; /// \TODO : fix the trouble (vtk?)
313 } // if spacePosition
317 // Alphabetical order
318 for (i=0; i<sizeFilenames; i++)
320 for (ii=i; ii<sizeFilenames; ii++)
322 if (Filenames[i]>Filenames[ii])
324 tmpString=Filenames[i];
325 Filenames[i]=Filenames[ii];
326 Filenames[ii]=tmpString;
331 // Creating SimpleFilenames
332 unsigned int lenghtBasePath = basePath.length();
333 for (i=0; i<sizeFilenames; i++)
335 SimpleFilenames.push_back( Filenames[i].substr( lenghtBasePath ) );
345 int FilesFromDirectory::Explore(std::string const &dirpath, bool recursive)
348 int numberOfFiles = 0;
349 std::string fileName;
350 std::string dirName = NormalizePath(dirpath);
352 WIN32_FIND_DATA fileData;
353 //assert( dirName[dirName.size()-1] == '' );
354 HANDLE hFile = FindFirstFile((dirName+"*").c_str(), &fileData);
356 for(BOOL b = (hFile != INVALID_HANDLE_VALUE); b;
357 b = FindNextFile(hFile, &fileData))
359 fileName = fileData.cFileName;
360 if ( fileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
362 // Need to check for . and .. to avoid infinite loop
363 if ( fileName != "." && fileName != ".." && recursive )
365 numberOfFiles += Explore(dirName+fileName, recursive);
370 // std::string temp = "\"" +dirName+fileName + "\"";
371 std::string temp = dirName+fileName;
372 std::string::size_type spacePosition = temp.find_first_of(' ');
373 if (spacePosition != std::string::npos)
375 std::cout << "=========================================== File name : [" <<temp <<
376 "] contains space(s); Discarted !" << std::endl;
377 temp.insert(spacePosition, "\\");
378 continue; /// \TODO : fix the trouble (vtk?)
380 Filenames.push_back(temp);
384 DWORD dwError = GetLastError();
385 if (hFile != INVALID_HANDLE_VALUE)
387 if (dwError != ERROR_NO_MORE_FILES)
390 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|
391 FORMAT_MESSAGE_FROM_SYSTEM|
392 FORMAT_MESSAGE_IGNORE_INSERTS,
394 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
395 (LPTSTR) &lpMsgBuf,0,NULL);
397 //gdcmErrorMacro("FindNextFile error. Error is " << (char *)lpMsgBuf
398 // <<" for the directory : "<<dirName);
403 // Real POSIX implementation: scandir is a BSD extension only, and doesn't
404 // work on debian for example
406 DIR* dir = opendir(dirName.c_str());
412 // According to POSIX, the dirent structure contains a field char d_name[]
413 // of unspecified size, with at most NAME_MAX characters preceeding the
414 // terminating null character. Use of other fields will harm the porta-
415 // bility of your programs.
419 for (d = readdir(dir); d; d = readdir(dir))
421 fileName = dirName + d->d_name;
422 std::string temp = fileName;
423 if( stat(fileName.c_str(), &buf) != 0 )
425 //gdcmErrorMacro( strerror(errno) );
427 if ( S_ISREG(buf.st_mode) ) //is it a regular file?
429 if ( d->d_name[0]!='.')
432 std::string::size_type spacePosition = temp.find_first_of(' ');
433 if (spacePosition != std::string::npos)
435 std::cout << "=========================================== File name : [" <<temp <<
436 "] contains space(s); Discarted !" << std::endl;
437 temp.insert(spacePosition, "\\");
438 continue; /// \TODO : fix the trouble (vtk?)
440 Filenames.push_back(temp);
444 else if ( S_ISDIR(buf.st_mode) ) //directory?
446 if ( d->d_name[0] != '.' && recursive ) //we also skip hidden files
448 numberOfFiles += Explore( fileName, recursive);
453 //gdcmErrorMacro( "Unexpected error" );
457 if( closedir(dir) != 0 )
459 //gdcmErrorMacro( strerror(errno) );
463 std::string tmpString;
464 int i,ii,sizeFilenames = Filenames.size();
465 for (i=0; i<sizeFilenames; i++)
467 for (ii=i; ii<sizeFilenames; ii++)
469 if (Filenames[i]>Filenames[ii])
471 tmpString=Filenames[i];
472 Filenames[i]=Filenames[ii];
473 Filenames[ii]=tmpString;
478 return numberOfFiles;
483 // EO namespace bbstd