POSIX C function nftw(p) walks directory tree and reports data on files.
Its just do something like piping of output of following line:
find| xargs stat
Below is 100+ lines C++ version of previous line.
g++ exnftw.cpp -o nftw
------------%<---------------
#include <ftw.h>
#include <stdio.h>
#include <map>
#include <string>
/* 2008, Author: R.Gritsulyak
* public domain;
* g++ exnftw.cpp -o nftw
* no warranty for this utility.
* patch sendto: roman.gritsulyak@gmail.com
*
* example for:
int nftw(const char *path, int (*fn)(const char *,
const struct stat *, int, struct FTW *), int depth, int flags);
*/
int fnfn(const char *path, const struct stat *ptr,int type, struct FTW *pft)
{
const char *sflag;
switch (type)
{
case FTW_NS:
sflag="FTW_NS: no permission: exit by error;";
break;
case FTW_DNR:
sflag="FTW_DNR: can not read dir; no further reads in;";
break;
case FTW_SLN:
sflag="FTW_SLN: symbolic link on unknown path;";
break;
case FTW_SL:
sflag="FTW_SL: should detect if only FTW_SL set;";
break;
case FTW_DP:
sflag="FTW_DP: directory; we have been in subdirs;";
break;
case FTW_D:
sflag="FTW_D: directory;";
break;
case FTW_F:
sflag="FTW_F: file;";
break;
default:
sflag="unknown:";
}
printf("path=%s\ntype=%s\n",path,sflag);
printf("stat.st_ino=%d\n",ptr->st_ino);
printf("stat.st_mode=%o\n",ptr->st_mode);
printf("stat.st_nlink=%d\n",ptr->st_nlink);
printf("stat.st_uid=0%o\n",ptr->st_dev);
printf("stat.st_gid=0%o\n",ptr->st_gid);
printf("stat.st_rdev=%d\n",ptr->st_rdev);
printf("stat.st_size=%d\n",ptr->st_size);
printf("stat.st_blksize=%u\n",ptr->st_blksize);
printf("stat.st_blocks=%u\n",ptr->st_blocks);
printf("stat.st_atime=%d\n",ptr->st_atime);
printf("stat.st_mtime=%d\n",ptr->st_mtime);
printf("stat.st_ctime=%d\n",ptr->st_ctime);
printf("FTW.base=%d\nFTW.level=%d\n",pft->base,pft->level);
return 0;
}
struct chvali
{
std::string ch;
int vali;
};
const int FLAGS=4;
chvali stra[] = {
{"FTW_CHDIR",FTW_CHDIR},
{"FTW_DEPTH",FTW_DEPTH},
{"FTW_MOUNT",FTW_MOUNT},
{"FTW_PHYS",FTW_PHYS}
};
int usage()
{
fprintf(stderr,"Usage: nftw FLAG1 FLAG2 .. FLAGn depth path\n");
fprintf(stderr,"FLAGx is FTW_CHDIR, FTW_DEPTH, FTW_MOUNT, FTW_PHYS\n");
fprintf(stderr,"depth # number of file descriptors to use\n");
fprintf(stderr,"man p nftw # for further details on args\n");
return 0;
}
int main(int argc, char ** argv)
{
char * inipath;
int i;
int idepth;
int iflags;
int curflag;
std::map<std::string,int> chv;
for(i=0;i<FLAGS;i++)
chv[stra[i].ch]=stra[i].vali;
if (argc < 3)
{
exit(1);
}
iflags = 0;
std::map<std::string,int> iter;
for(i=1; i<argc-2; i++)
{
if( chv.find(argv[i]) != chv.end() )
iflags = iflags | chv[argv[i]];
else
{
fprintf(stderr, "Wrong argument type:%s\n",argv[i]);
usage();
exit(-1);
}
}
inipath = argv[argc-1];
char *dum;
idepth = strtol(argv[argc-2], &dum, 0);
if(nftw(inipath,fnfn,idepth,iflags) != 0)
{
perror("nftw");
exit(2);
}
exit(0);
}
related ftw example
No comments:
Post a Comment