今天需要测试一下OJ产生的数据,文件太多,所以需要通过文件递归遍历调用shell命令,所以网上找了递归访问的,比之前window下的程序更简单清爽。
借鉴:http://www.cnblogs.com/xudong-bupt/p/3504442.html
Linux C 下面读取文件夹要用到结构体struct dirent,在头#include <dirent.h>中,如下:
#include <dirent.h>
struct dirent
{
long d_ino; /* inode number 索引节点号 */
off_t d_off; /* offset to this dirent 在目录文件中的偏移 */
unsigned short d_reclen; /* length of this d_name 文件名长 */
unsigned char d_type; /* the type of d_name 文件类型 */
char d_name [NAME_MAX+1]; /* file name (null-terminated) 文件名,最长255字符 */
}
其中d_type表明该文件的类型:文件(8)、目录(4)、链接文件(10)等。
下面程序,递归读取某文件夹及其子文件夹下所有文件名:
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <dirent.h>
5 #include <unistd.h>
6 int readFileList(char *basePath)
7 {
8 DIR *dir;
9 struct dirent *ptr;
10 char base[1000];
11
12 if ((dir=opendir(basePath)) == NULL)
13 {
14 perror("Open dir error...");
15 exit(1);
16 }
17
18 while ((ptr=readdir(dir)) != NULL)
19 {
20 if(strcmp(ptr->d_name,".")==0 || strcmp(ptr->d_name,"..")==0) ///current dir OR parrent dir
21 continue;
22 else if(ptr->d_type == 8) ///file
23 printf("d_name:%s/%s
",basePath,ptr->d_name);
24 else if(ptr->d_type == 10) ///link file
25 printf("d_name:%s/%s
",basePath,ptr->d_name);
26 else if(ptr->d_type == 4) ///dir
27 {
28 memset(base,'