使用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\n",ptr->d_name);
}
closedir(dir);
return 0;
}
int main(int argc,char **argv){
if(argc<2){
printf("listfiles <path>\n");
exit(1);
}
if(my_dir(argv[1])<0){
printf("error listfiles\n");
}else{
printf("listfiles ok\n");
}
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