2008-11-10
Linux下显示某一目录下文件名列表的C程序
标签:c语言, Develop, Freebsd/Unix服务器以下是一个Linux/Unix下显示某一目录下文件列表的C程序,相当于最基本的ls命令的功能,显示的内容报告该目录下的子目录以及文件名:
- #include <sys/types.h>
- #include <dirent.h>
- #include <stdio.h>
- #include <errno.h>
- int main(int argc,char *argv[])
- {
- DIR *dp;
- struct dirent *dirp;
- int n=0;
- if (argc!=2)
- {
- printf("a single argument is required\n");
- exit(0);
- }
- if((dp=opendir(argv[1]))==NULL)
- printf("can't open %s",argv[1]);
- while (((dirp=readdir(dp))!=NULL) && (n<=50))
- {
- if (n % 1 == 0) printf("\n");
- n++;
- printf("%10s ",dirp->d_name);
- }
- printf("\n");
- closedir(dp);
- exit(0);
- }
如果只是显示该目录下的子目录名,则需要使用如下程序(其中还包括了一个对于子目录名的冒泡排序):
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <dirent.h>
- #include <stdio.h>
- #include <errno.h>
- int main(int argc,char *argv[])
- {
- DIR *dp;
- struct dirent *dirp;
- struct stat buf;
- char tempDirName[100];
- char dirNames[100][100];
- int n=0,i=0,j=0,dirCount=0;
- if (argc!=2)
- {
- printf("a single argument is required\n");
- exit(0);
- }
- strcat(tempDirName,argv[1]);//get the directory name
- if((dp=opendir(argv[1]))==NULL)
- printf("can't open %s",argv[1]);
- while (((dirp=readdir(dp))!=NULL) && (n<=50))
- {
- //if (n % 1 == 0) printf("\n");
- n++;
- //printf("%10s ",dirp->d_name);
- strcpy(tempDirName,"");//clear
- strcat(tempDirName,argv[1]);//get the directory name
- strcat(tempDirName,dirp->d_name);
- if(IsDirectory(tempDirName))
- {
- //printf("\tDirectory!!!!");
- strcpy(dirNames[dirCount],dirp->d_name);
- //printf("\ttest:%s",dirNames[dirCount]);
- dirCount++;
- }
- }
- printf("\n");
- /* Sort */
- for(j=0;j<dirCount;j++)
- {
- for (i=0;i<dirCount-j;i++)
- if (strcmp( dirNames[i], dirNames[i+1])>0)
- {
- //printf("\nexchange %s and %s",dirNames[i], dirNames[i+1]);
- strcpy(tempDirName,dirNames[i]);
- strcpy(dirNames[i],dirNames[i+1]);
- strcpy(dirNames[i+1],tempDirName);
- }
- }
- /* Output sorted list: */
- for( i = 0; i < dirCount; ++i )
- printf( "\n%s ", dirNames[i] );
- printf( "\n" );
- closedir(dp);
- exit(0);
- }
- int IsDirectory(const char *dirname)
- {
- struct stat sDir;
- if (stat(dirname,&sDir) < 0)
- {
- return 0;
- }
- if(S_IFDIR == (sDir.st_mode & S_IFMT))
- {
- return 1;
- }
- else
- {
- return 0;
- }
- }
本文可以自由转载,转载时请保留全文并注明出处:
转载自仲子说 [ http://www.wangzhongyuan.com/ ]
原文链接:http://www.wangzhongyuan.com/archives/487.html
Spirit said,
2008年11月11日 at 18:59
这么复杂啊……
仲远 said,
2008年11月12日 at 12:37
第一个程序功能最基本,所以简单些;第二个程序加上了对于子目录的判断以及排序功能。