]> Creatis software - crea.git/blob - src/creaFilesFromDirectory.cxx
#3180 crea Feature New Normal Future - Set wx-config for wxWidgets 2.8
[crea.git] / src / creaFilesFromDirectory.cxx
1 /*
2 # ---------------------------------------------------------------------
3 #
4 # Copyright (c) CREATIS (Centre de Recherche en Acquisition et Traitement de l'Image 
5 #                        pour la Santé)
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
9 #
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.
16 #
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
21 #  liability. 
22 #
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 # ------------------------------------------------------------------------ 
26 */ 
27
28 /*=========================================================================
29                                                                                 
30   Program:   crea
31   Module:    $RCSfile: creaFilesFromDirectory.cxx,v $
32   Language:  C++
33   Date:      $Date: 2012/11/15 10:43:26 $
34   Version:   $Revision: 1.7 $
35                                                                                 
36    
37      This software is distributed WITHOUT ANY WARRANTY; without even
38      the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
39      PURPOSE.  See the above copyright notices for more information.
40                                                                                 
41 =========================================================================*/
42
43
44 /**
45  *  \file 
46  *  \brief  class Exception:generic class for throwing any exception (header) 
47  *
48  *    Long description:
49  */
50 #ifdef _MSC_VER
51    #include <windows.h>
52    #include <direct.h>
53 #else
54    #include <dirent.h>   
55    #include <sys/types.h>
56 #endif
57
58 #include <sys/stat.h>  //stat function
59
60  #include "creaFilesFromDirectory.h"
61  #include "creaMessageManager.h"
62
63 namespace crea
64
65
66 /**
67  * \brief   Add a SEPARATOR to the end of the name if necessary
68  * @param   pathname file/directory name to normalize 
69  */
70 std::string DirList::NormalizePath(std::string const &pathname)
71 {
72
73
74 #ifdef _WIN32
75    const char FILESEPARATOR = '\\';
76 #else
77    const char FILESEPARATOR = '/';
78 #endif
79
80         
81    std::string name = pathname;
82    int size = name.size();
83
84 //   if ( name[size-1] != SEPARATOR_X && name[size-1] != SEPARATOR_WIN )
85    if ( name[size-1] != FILESEPARATOR )
86    {
87       name += FILESEPARATOR;
88    }
89    return name;
90 }  
91 /**
92  * \brief   Explore a directory with possibility of recursion
93  *          return number of files read
94  * @param  dirpath   directory to explore
95  * @param  recursive whether we want recursion or not
96  */
97 int DirList::Explore(std::string const &dirpath, bool recursive)
98 {
99    int numberOfFiles = 0;
100    std::string fileName;
101    std::string dirName = NormalizePath(dirpath);
102 #ifdef _MSC_VER
103    WIN32_FIND_DATA fileData;
104    //assert( dirName[dirName.size()-1] == '' );
105    HANDLE hFile = FindFirstFile((dirName+"*").c_str(), &fileData);
106
107    for(BOOL b = (hFile != INVALID_HANDLE_VALUE); b;
108        b = FindNextFile(hFile, &fileData))
109    {
110       fileName = fileData.cFileName;
111       if ( fileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
112       {
113          // Need to check for . and .. to avoid infinite loop
114          if ( fileName != "." && fileName != ".." && recursive )
115          {
116             numberOfFiles += Explore(dirName+fileName,recursive);
117          }
118       }
119       else
120       {
121          Filenames.push_back(dirName+fileName);
122          numberOfFiles++;
123       }
124    }
125    DWORD dwError = GetLastError();
126    if (hFile != INVALID_HANDLE_VALUE) 
127       FindClose(hFile);
128    if (dwError != ERROR_NO_MORE_FILES) 
129    {
130       LPVOID lpMsgBuf;
131       FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|
132                     FORMAT_MESSAGE_FROM_SYSTEM|
133                     FORMAT_MESSAGE_IGNORE_INSERTS,
134                     NULL,GetLastError(),
135                     MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
136                     (LPTSTR) &lpMsgBuf,0,NULL);
137
138       creaError("FindNextFile error. Error is " << (char *)lpMsgBuf
139                    <<" for the directory : "<<dirName);
140       return -1;
141    }
142
143 #else
144   // Real POSIX implementation: scandir is a BSD extension only, and doesn't 
145   // work on debian for example
146
147    DIR* dir = opendir(dirName.c_str());
148    if (!dir)
149    {
150       return 0;
151    }
152
153    // According to POSIX, the dirent structure contains a field char d_name[]
154    // of unspecified size, with at most NAME_MAX characters preceeding the
155    // terminating null character. Use of other fields will harm the  porta-
156    // bility of your programs.
157
158    struct stat buf;
159    dirent *d;
160    for (d = readdir(dir); d; d = readdir(dir))
161    {
162            
163       fileName = dirName + d->d_name;
164       if( stat(fileName.c_str(), &buf) != 0 )
165       {
166          //gdcmErrorMacro( strerror(errno) );
167       }
168       if ( S_ISREG(buf.st_mode) )    //is it a regular file?
169       {
170                   //printf("EED DirList::Explore [%s]\n" , d->d_name );
171                   if ( d->d_name[0]!='.')
172                   {     
173                  Filenames.push_back( fileName );
174                  numberOfFiles++;
175                   }
176       }
177       else if ( S_ISDIR(buf.st_mode) ) //directory?
178       {
179          if ( d->d_name[0] != '.' && recursive ) //we also skip hidden files
180          {
181             numberOfFiles += Explore( fileName, recursive);
182          }
183       }
184       else
185       {
186          //gdcmErrorMacro( "Unexpected error" );
187          return -1;
188       }
189    }
190    if( closedir(dir) != 0 )
191    {
192       //gdcmErrorMacro( strerror(errno) );
193    }
194 #endif
195
196   return numberOfFiles;
197 }
198
199 }