#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); /*判斷輸入的文件路徑是否目錄,若是目錄,則往下執(zhí)行,分析目錄下的文件*/ 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()必須循環(huán)調(diào)用,要讀完整個(gè)目錄的文件,readdir才會(huì)返回NULL 若未讀完,就讓他循環(huán)*/ while(filename = readdir(dp)) { /*判斷一個(gè)文件是目錄還是一個(gè)普通文件*/ char file_path[200]; bzero(file_path,200); strcat(file_path,path); strcat(file_path,"/"); strcat(file_path,filename->d_name); /*在linux下每一個(gè)目錄都有隱藏的. 和..目錄,一定要把這兩個(gè)排除掉。因?yàn)闆]有意義且會(huì)導(dǎo)致死循環(huán)*/ 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); } }}
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注