Recursively prints the file name and file size of all files under the current directory, compiled under ubuntu14.04:
/************************************************************************* > File name:dirwalk.c > Author: > Mail: > Created time:tue 11:56:38 AM CST **************************************************** ********************/#include<stdio.h>#include<sys/types.h>#include<sys/stat.h>#include<fcntl.h>#include<unistd.h>#include<stdlib.h>#include<string.h>#include<dirent.h>#defineMAX_PATH 1024/*dirwalk:apply FCN to all files in Dir*/voidDirwalk (Char* Dir,void(*FCN) (Char*)){ structDirent *DP; DIR*DFD; CharName[max_path]; if(DFD = Opendir (dir)) = =NULL) {fprintf (stderr,"Dirwalk:can ' t open%s\n", dir); return; } while(DP = Readdir (DFD))! =NULL) { if(strcmp (Dp->d_name,".") ==0|| strcmp (Dp->d_name,"..") ==0) { Continue; } if(Strlen (dir) + strlen (dp->d_name) +2>sizeof(name)) {fprintf (stderr,"%s/%s too long\n", dir, dp->d_name); }Else{sprintf (name,"%s/%s", dir, dp->d_name); (*FCN) (name); }} closedir (DFD);}/*Print the file name and the size of the "name"*/voidFsize (Char*name) { structstat st_buf; if(Stat (name, &ST_BUF) <0) {fprintf (stderr,"Fsize:can ' t access%s\n", name); return; } if((St_buf.st_mode & s_ifmt) = =S_ifdir) {printf ("%ld%s\n", st_buf.st_size, name); Dirwalk (name, fsize); printf ("\ n"); }Else{printf ("%ld%s\n", st_buf.st_size, name); }}intMainintargcChar*argv[]) { if(ARGC = =1) Fsize ("."); while(--argc) fsize (*++argv); return 0;}
Recursively print file names and file sizes for all files in the current directory