1. 在Linux下要判断一个路径是否是目录,及遍历这个路径下的所有文件,可以使用以下方式:
主演使用的函数是:
int lstat(const char *, struct stat):取得一个路径的信息,可以从这个信息中得到是否及目录还是文件。其他属性参考man
S_ISDIR():判断是否是目录,传入参数是stat.st_mode
DIR * opendir(const char *):打开指定路径
struct dirent readdir(DIR *):打开指定目录的子路径,可以反复调用本函数来得到制定目录的所有子路径信息。当执行到最后一个目录或者文件的时候,将返回NULL
综上,遍历一个目录下的所有文件的代码如下所示:
#include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #include <stdio.h> #include <stdlib.h> #include <dirent.h> int main(void) { struct stat fStat; DIR *dir; struct dirent *fileInfo = NULL; if (-1 == lstat("test.txt", &fStat)) { perror(""); return -1; } if (S_ISDIR(fStat.st_mode)) { printf("INFO: The path is a directory!\n"); } else { printf("INFO: The path is a file!\n"); return 1; } //If it is a dir, print the files' names in this directory. dir = opendir("test.txt"); if (NULL == dir) { perror(""); return -1; } fileInfo = readdir(dir); while (NULL != fileInfo) { printf("INFO: File name is %s!\n", fileInfo->d_name); fileInfo = readdir(dir); } return 1; }