您的位置:首页 > 运维架构 > Linux

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

2004-09-10 12:31 1186 查看
也是很简单的小程序,用到了一些目录操作

#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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: