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
#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
相关文章推荐
- linux下使用系统调用编程实现copy命令功能
- Linux C系统编程:使用线程池,实现cp功能
- Linux系统编程:pipe匿名管道的使用,实现linux命令下管道命令
- 使用 Linux 系统调用的内核命令
- 使用 Linux 系统调用的内核命令
- 使用 Linux 系统调用的内核命令
- 实现linux cp命令( 系统调用版 )
- 在linux上使用rlwrap实现像dos功能使用上下键查看命令
- linux基础编程 共享内存 使用内存映射接口mmap系统调用
- 用c语言程序实现系统的cp命令 在linux下调用syscalls.h头文件
- 使用 Linux 系统调用的内核命令
- Linux中实现MSDN的功能查系统调用
- 使用 Linux 系统调用的内核命令
- Linux系统使用crontab命令实现计划任务
- linux下c编程系统调用之有名管道FIFO函数的使用及案例
- 使用 Linux 系统调用的内核命令
- 使用 Linux 系统调用的内核命令
- 使用 Linux 系统调用的内核命令
- 基于Linux系统调用使用php实现一个在线编译运行C语言程序的系统
- linux系统调用之文件:递归实现tree命令