Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-04-09 07:49:13

0001 /**
0002 fts_test.cc
0003 =============
0004 
0005 ::
0006 
0007     ./fts_test.sh 
0008 
0009 
0010 * https://stackoverflow.com/questions/12609747/traversing-a-filesystem-with-fts3
0011 
0012 **/
0013 
0014 #include <cstdlib>
0015 #include <cstdio>
0016 #include <sys/types.h>
0017 #include <fts.h>
0018 #include <cstring>
0019 #include <errno.h>
0020 
0021 int compare(const FTSENT** one, const FTSENT** two)
0022 {
0023     return (strcmp((*one)->fts_name, (*two)->fts_name));
0024 }
0025 void indent(int i)
0026 { 
0027     for(; i > 0; i--) printf("   ");
0028 }
0029 
0030 
0031 
0032 // traverses tree starting from base and outputs names of regular files encountered
0033 // directories are just skipped
0034 void traverse(char* base)
0035 {
0036     char* path[2] {base, nullptr};
0037 
0038     FTS* fs = fts_open(path,FTS_COMFOLLOW|FTS_NOCHDIR,&compare);
0039     if(fs == nullptr) return ; 
0040 
0041     FTSENT* node = nullptr ;
0042     while((node = fts_read(fs)) != nullptr)
0043     {
0044         switch (node->fts_info) 
0045         {
0046             case FTS_D :   break ;     // NB directories are just skipped 
0047             case FTS_F :
0048             case FTS_SL:               // only regular files or symbolic links are acted upon 
0049                 //indent(node->fts_level);
0050                 printf("node->fts_level %d node.fts_name %20s node.fts_path %s relp %s \n", 
0051                            node->fts_level, 
0052                            node->fts_name, 
0053                            node->fts_path, 
0054                            node->fts_path+strlen(base)+1
0055                            );
0056                 break;
0057             default:
0058                 break;
0059         }
0060     }
0061     fts_close(fs);
0062 }
0063 
0064 int main(int argc, char** argv)
0065 {
0066     if (argc<2)
0067     {
0068         printf("Usage: %s <path-spec>\n", argv[0]);
0069         exit(255);
0070     }
0071 
0072     traverse(argv[1]); 
0073 
0074     return 0;
0075 }
0076 
0077