linux下使用系统调用编程实现dir命令功能

王朝system·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

也是很简单的小程序,用到了一些目录操作

#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

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航