#include <stdio.h>#include <dirent.h>#include <stdlib.h>#include <string.h>#include <sys/types.h>#include <sys/stat.h>void dir_oper(char const*path);int main(int argc, char const *argv[]){ char const*path = argv[1]; struct stat s_buf; /*獲取文件信息,把信息放到s_buf中*/ stat(path,&s_buf); /*判斷輸入的文件路徑是否目錄,若是目錄,則往下執行,分析目錄下的文件*/ if(S_ISDIR(s_buf.st_mode)) { dir_oper(path); } /*若輸入的文件路徑是普通文件,則打印并退出程序*/ else if(S_ISREG(s_buf.st_mode)) { PRintf("[%s] is a regular file/n",path); return 0; } return 0;}void dir_oper(char const*path){ printf("[%s] it is a dir/n",path); struct dirent *filename; struct stat s_buf; DIR *dp = opendir(path); /*readdir()必須循環調用,要讀完整個目錄的文件,readdir才會返回NULL 若未讀完,就讓他循環*/ while(filename = readdir(dp)) { /*判斷一個文件是目錄還是一個普通文件*/ char file_path[200]; bzero(file_path,200); strcat(file_path,path); strcat(file_path,"/"); strcat(file_path,filename->d_name); /*在linux下每一個目錄都有隱藏的. 和..目錄,一定要把這兩個排除掉。因為沒有意義且會導致死循環*/ if(strcmp(filename->d_name,".")==0||strcmp(filename->d_name,"..")==0) { continue; } /*獲取文件信息,把信息放到s_buf中*/ stat(file_path,&s_buf); /*判斷是否目錄*/ if(S_ISDIR(s_buf.st_mode)) { dir_oper(file_path); printf("/n"); } /*判斷是否為普通文件*/ if(S_ISREG(s_buf.st_mode)) { printf("[%s] is a regular file/n",file_path); } }}
新聞熱點
疑難解答