以下是一个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]);
if((dp=opendir(argv[1]))==NULL)
printf("can't open %s", argv[1]);
while(((dirp=readdir(dp))!=NULL) && (n<=50))
{
n++;
strcpy(tempDirName, "");
strcat(tempDirName, argv[1]);
strcat(tempDirName, dirp->d_name);
if(IsDirectory(tempDirName))
{
strcpy(dirNames[dirCount], dirp->d_name);
dirCount++;
}
}
printf("\n");
for(j=0; j<dirCount; j++)
{
for(i=0; i<dirCount; i++)
if(strcmp(dirNames[i], dirNames[i+1]) > 0)
{
strcpy(tempDirName, dirNames[i]);
strcpy(dirNames[i], dirNames[i+1]);
strcpy(dirNames[i+1], tempDirName);
}
}
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;
return 0;
}
From:
作者:仲子说