也是很简单的小程序,用到了一些目录操作
#include <unistd.h> #include <stdio.h> #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <time.h>
static int get_info(const char * filename) { struct stat statbuf; if(stat(filename,&statbuf)==-1) { printf("%s\n",filename); return(1); } if(S_ISDIR(statbuf.st_mode)) printf("%s\t Directory\tmodified at %s",filename,ctime(&statbuf.st_mtime)); if(S_ISREG(statbuf.st_mode)) printf("%s\tsize:%ld bytes\tmodified at %s",filename,statbuf.st_size,ctime(&statbuf.st_mtime)); return(0); }
int main(int argc,char **argv) { DIR * dirp; struct dirent * direntp;
if((dirp=opendir(argv[1]))) { while((direntp=readdir(dirp))!=NULL) get_info(direntp->d_name); /* printf("%s\t",direntp->d_name);*/ closedir(dirp); exit(1); } else { printf("Error\n"); exit(1); } }
其实程序还有一点问题,在当前目录下使用效果很好,但是如果dir的是一个其他的路径,就无法显示一些文件的具体信息,具体来说,就是stat(filename,&statbuf)会等于-1,如果只是希望显示目录名和文件名,可以把get_info函数删掉,把mian函数里加注释的那一句去掉注释就可以了
再给大家介绍一个不错的网站,IBM的开发者园地linux版
http://www-900.ibm.com/developerWorks/cn/linux/index.shtml
|