主要函數: stat(),opendir(),readdir(),
主要結構體:struct dirent 和 struct stat
主要宏:S_ISDIR(), S_ISREG()
函數 stat()用于獲取一個文件路徑的信息,并把獲取到的信息放到結構體 struct stat 中
函數 opendir()用于生成一個目錄指針DIR
函數readdir()用于讀取目錄指針 DIR 中的信息,返回的值為一個 struct dirent 結構體
結構體struct dirent 用于保存一個目錄的屬性。這里用到的只是該結構體的 d_name 成員,用于保存目錄下的文件名
結構體 struct stat 用于保存 一個文件路徑的信息
宏S_ISDIR()用于判斷一個文件路徑是不是一個目錄,是則返回1,否則返回0
宏S_ISREG()用于判斷一個文件路徑是不是一個普通文件,是則返回1,否則返回0
下面給出代碼:
#include <stdio.h>#include <dirent.h>#include <stdlib.h>#include <string.h>#include <sys/types.h>#include <sys/stat.h>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)) { PRintf("[%s] it is a dir/n",path); struct dirent *filename; 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); /*獲取文件信息,把信息放到s_buf中*/ stat(file_path,&s_buf); /*判斷是否目錄*/ if(S_ISDIR(s_buf.st_mode)) { printf("[%s] is a dir/n",file_path); } /*判斷是否為普通文件*/ if(S_ISREG(s_buf.st_mode)) { printf("[%s] is a regular file/n",file_path); } } } /*若輸入的文件路徑是普通文件,則打印并退出程序*/ else if(S_ISREG(s_buf.st_mode)) { printf("[%s] is a regular file/n",path); return 0; } return 0;}
新聞熱點
疑難解答