入门客AI创业平台(我带你入门,你带我飞行)
博文笔记

使用readdir系统调用模拟shell ls功能

创建时间:2016-08-08 投稿人: 浏览次数:563

使用readdir系统调用模拟shell ls功能

使用到的有是三个系统调用

opendir 用来打开参数name指定的目录, 并返回DIR*形态的目录流, 和open()类似, 接下来对目录的读取和搜索都要使用此返回值。

readdir 返回参数dir目录流的下个目录进入点。

closedir 关闭参数dir所指的目录流



 #include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<dirent.h>
//浏览目录显示目录下信息
int my_dir(const char *path){
        DIR *dir;
        struct dirent *ptr;
        if((dir=opendir(path))==NULL){
                perror("opendir");
                return -1;
        }
        while((ptr=readdir(dir))!=NULL){//需要循环
                printf("file name:%s ",ptr->d_name);
        }
        closedir(dir);
        return 0;
}
int main(int argc,char **argv){


        if(argc<2){


                printf("listfiles <path> ");
                exit(1);
        }


        if(my_dir(argv[1])<0){
                printf("error listfiles ");
        }else{
                printf("listfiles ok ");
        }
        return 0;
}


编译运行

 gcc -o my_showfiles my_showfiles.c 
zhangzhengyi@SERVER:~/ctest$ ./my_showfiles /tmp
file name:.Test-unix
file name:systemd-private-86ec608241704315bce2002b49820d9d-systemd-timesyncd.service-5QeSuS
file name:.
file name:.font-unix
file name:.XIM-unix
file name:hsperfdata_zhangzhengyi
file name:test
file name:.ICE-unix
file name:tomcat7-tomcat7-tmp
file name:hsperfdata_tomcat7
file name:ehcache
file name:..
file name:.X11-unix
listfiles ok
                      

声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
  • 上一篇:没有了
  • 下一篇:没有了
未上传头像