| 关键词: nbsp include dirNames printf tempDirName argv dirCount int 目录名 strcpy |
以下是一个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 "); 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++; printf("%10s", dirp->d_name); } printf(" "); 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 "); 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(" "); 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(" %s", dirNames[i]); printf(" "); 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;} |
|
声明:文章版权归原作者所有 部分文章转自互联网 如有侵权请联系
[邮箱地址] 删除
|