Linux 下遍历某文件夹下文件(不迭代进入子目录)

原文地址:http://www.wangzhongyuan.com/archives/487.html

以下是一个Linux/Unix下显示某一目录下文件列表的C程序,相当于最基本的ls命令的功能,显示的内容报告该目录下的子目录以及文件名:

代码
1 #include <sys/types.h>
2 #include <dirent.h>
3 #include <stdio.h>
4 #include <errno.h>
5  int main(int argc,char *argv[])
6 {
7 DIR *dp;
8 struct dirent *dirp;
9 int n=0;
10 if (argc!=2)
11 {
12 printf("a single argument is required\n");
13 exit(0);
14 }
15 if((dp=opendir(argv[1]))==NULL)
16 printf("can't open %s",argv[1]);
17 while (((dirp=readdir(dp))!=NULL) && (n<=50))
18 {
19 if (n % 1 == 0) printf("\n");
20 n++;
21 printf("%10s ",dirp->d_name);
22 }
23 printf("\n");
24 closedir(dp);
25 exit(0);
26 }

 

如果只是显示该目录下的子目录名,则需要使用如下程序(其中还包括了一个对于子目录名的冒泡排序): 

代码
1 #include <sys/types.h>
2 #include <sys/stat.h>
3 #include <dirent.h>
4 #include <stdio.h>
5 #include <errno.h>
6
7  int main(int argc,char *argv[])
8 {
9 DIR *dp;
10 struct dirent *dirp;
11 struct stat buf;
12 char tempDirName[100];
13 char dirNames[100][100];
14 int n=0,i=0,j=0,dirCount=0;
15 if (argc!=2)
16 {
17 printf("a single argument is required\n");
18 exit(0);
19 }
20 strcat(tempDirName,argv[1]);//get the directory name
21   if((dp=opendir(argv[1]))==NULL)
22 printf("can't open %s",argv[1]);
23 while (((dirp=readdir(dp))!=NULL) && (n<=50))
24 {
25 //if (n % 1 == 0) printf("\n");
26   n++;
27 //printf("%10s ",dirp->d_name);
28   strcpy(tempDirName,"");//clear
29   strcat(tempDirName,argv[1]);//get the directory name
30 strcat(tempDirName,dirp->d_name);
31 if(IsDirectory(tempDirName))
32 {
33 //printf("\tDirectory!!!!");
34 strcpy(dirNames[dirCount],dirp->d_name);
35 //printf("\ttest:%s",dirNames[dirCount]);
36 dirCount++;
37 }
38 }
39 printf("\n");
40
41 /* Sort */
42 for(j=0;j<dirCount;j++)
43 {
44 for (i=0;i<dirCount-j;i++)
45 if (strcmp( dirNames[i], dirNames[i+1])>0)
46 {
47 //printf("\nexchange %s and %s",dirNames[i], dirNames[i+1]);
48 strcpy(tempDirName,dirNames[i]);
49 strcpy(dirNames[i],dirNames[i+1]);
50 strcpy(dirNames[i+1],tempDirName);
51 }
52 }
53
54 /* Output sorted list: */
55 for( i = 0; i < dirCount; ++i )
56 printf( "\n%s ", dirNames[i] );
57 printf( "\n" );
58
59 closedir(dp);
60 exit(0);
61 }
62
63 int IsDirectory(const char *dirname)
64 {
65 struct stat sDir;
66 if (stat(dirname,&sDir) < 0)
67 {
68 return 0;
69 }
70 if(S_IFDIR == (sDir.st_mode & S_IFMT))
71 {
72 return 1;
73 }
74 else
75 {
76 return 0;
77 }
78 }
posted @ 2010-02-05 12:59  boymgl  阅读(2988)  评论(0编辑  收藏  举报