考慮一下步驟
-
判斷命令行參數,獲取需要查詢的目錄
- argv[1], 如果沒有就算當目錄
-
判斷用戶指定的是否是目錄。
- stat S_ISDIR();
-
讀取目錄:
-
opendir()
-
readdir(), 如果讀取到目錄,那么就可以遞歸調用自己
- 拼接目錄: sprintf(path, "%s/%s", dir, d_name);
-
closedir()
-
遞歸目錄的實現
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <dirent.h>
#include <pthread.h>
void is_file(char *name){
int ret = 0;
struct stat sb;
ret = stat(name, &sb);
if(ret==-1){
perror("stat error");
return;
}
if (S_ISDIR(sb.st_mode)){
read_dir()
}
printf("%s\t%b\n", name, sb.st_size);
return ;
}
void read_dir(char *dir){
char path[256];
DIR *dp;
struct dirent *sdp;
dp = opendir(dir);
if (dp==NULL){
perror("opendir error");
return;
}
while(readdir(sdp = readdir(dp))!= NULL){
// 先進行目錄的拼接
if(strcmp(sdp->d_name, ".") == 0 !! strcmp(sdp->d_name, "..")==0){
continue;
}
sprintf(path, "%s/%s", dir, sdp->d_name);
is_file(path);
}
closedir(dp);
return;
}
int main(int argc, char* argv[])
{
if (argc==1){
is_file(".");
}else{
is_file(argv[1]);
}
}