- 论坛徽章:
- 0
|
初学linux c ,今天看到第三章的一个例子:
这个程序有一个参数.如果这个参数是一个文件名,我们输出这个文件的大小和最后修改的时间,如果是一个目录我们输出这个目录下所有文件的大小和修改时间
- #include <stdio.h>
- #include <stdlib.h>
- #include <errno.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <dirent.h>
- #include <time.h>
- static int get_file_size_time(const char *filename){
- struct stat statbuf;
- if(stat(filename,&statbuf)==-1){
- printf("Get stat on %s Error: %s \n",filename,strerror(errno));
- return(-1);
- }
- if(S_ISDIR(statbuf.st_mode))return(1);
- if(S_ISREG(statbuf.st_mode)) printf("%s size: %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;
- int stats;
- if(argc!=2){
- printf("Usage: %s filename\n\a",argv[0]);
- exit(1);
- }
- if(((stats=get_file_size_time(argv[1]))==0)||(stats==-1))exit(1);
- if((dirp=opendir(argv[1]))==NULL){
- printf("Open Directory %s Error: %s\n",argv[1],strerror(errno));
- exit(1);
- }
- while((direntp=readdir(dirp))!=NULL)
- if(get_file_size_time(direntp-<d_name)==-1)break;
- closedir(dirp);
- exit(1);
- }
复制代码
这个程序在输入文件的时候正常,但输入目录的时候,有时候就会出错
- [root@cent52 3.dirfind]# ls
- dirf dirf.c kk
- [root@cent52 3.dirfind]# cd kk
- [root@cent52 kk]# ls
- dirf dirf.c
- [root@cent52 3.dirfind]# ./dirf kk
- dirf size: 6091 bytes modified at Fri Sep 12 17:29:29 2008
- dirf.c size: 958 bytes modified at Wed Sep 17 21:07:27 2008
复制代码
这样就没有问题,但下面就有问题
- [root@cent52 kk]# ls
- dirf dirf.c
- [root@cent52 kk]# cp /etc/* .
- [root@cent52 kk]# ls
- adjtime login.defs
- aliases logrotate.conf
- aliases.db ltrace.conf
- anacrontab mailcap
- at.deny mail.rc
- autofs_ldap_auth.conf man.config
- auto.master mime.types
- auto.misc mke2fs.conf
- auto.net modprobe.conf
- auto.smb modprobe.conf.BeforeVMwareToolsInstall
- bashrc motd
- .....很多文件省略, 但没有子目录的。
- [root@cent52 kk]# cd ..
- [root@cent52 3.dirfind]# ls
- dirf dirf.c kk
- [root@cent52 3.dirfind]# ./dirf kk
- Get stat on mtools.conf Error: No such file or directory
复制代码
不知道哪里的问题? |
|