linux 下scandir顯示指定目錄下檔案程式碼 c 實現
阿新 • • 發佈:2019-01-26
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/types.h>
//#include <assert.h>
//#include <ctype.h>
//#include <errno.h>
/*int scandir(const char* dirname, dirent*** name_list,
int (*filter)(const dirent*),
int (*comparator)(const dirent**, const dirent**))*/
extern int alphasort(const struct dirent** a, const struct dirent** b);
int isDir(char *filename)
{
struct stat stat;
lstat(filename, &stat);
printf("%s size is : %d\n",filename,stat.st_size);
if (S_ISDIR(stat.st_mode))
{
return 1;
}
//stat(filename,&info);
//if(S_ISDIR(info.st_mode))
// return 1;
return 0;
}
static int filter_dot(const struct dirent *d)
{
return (strcmp(d->d_name, "..") && strcmp(d->d_name, "."));
}
int myscandir(char *dir)
{
int entries = 0;
struct dentry *dentries;
struct dirent **namelist = NULL;
int ret = -1;
if (dir)
{
entries = scandir(dir, &namelist, filter_dot, (void*)alphasort);
}
if(entries == -1)
{
printf("arg is a file or not exit: %s, please set a dir \n",dir);
}
for(int i=0;i<entries;i++)
{
int len = strlen(dir) + 1 + strlen(namelist[i]->d_name) + 1;
char *path = malloc(len * sizeof(char));
if(path)
{
strcpy(path,dir);
strcat(path,"/");
strcat(path,namelist[i]->d_name);
}
else
{
printf("malloc fail in myscandir\n");
return -1;
}
#ifndef DT_DIR
#define DT_DIR 4
#endif
//or isDir(path)
if(namelist[i]->d_type == DT_DIR)
{
free(namelist[i]);
printf(" dir : %s\n",path);
ret = myscandir(path);
free(path);
}
else
{
free(namelist[i]);
ret = 0;
printf("file : %s\n",path);
free(path);
}
}
return ret;
}
char* getdir(int argc,char **argv)
{
char *optstring = "d:";
char op;
char *dir = NULL;
extern char* optarg;
while((op=getopt(argc,argv,optstring)) != -1)
{
switch (op)
{
case 'd':
if(!optarg)
return NULL;
dir = malloc(strlen(optarg)+1);
if(!dir)
{
printf("malloc fail in getdir \n");
return NULL;
}
strcpy(dir,optarg);
break;
case '?':
default:
printf("option is invalid or need arg\n");
printf("Usage: -d dir or -d file or no option indicate current dir\n");
break;
}
}
if(!dir)
{
dir = getcwd(NULL,0);
if(!dir)
{
printf("malloc fail in getdir \n");
return NULL;
}
}
return dir;
}
int main(int argc,char *argv[])
{
char *dir = NULL;
dir = getdir(argc,argv);
if(dir)
{
myscandir(dir);
free(dir);
return 0;
}
printf("error find \n");
return -1;
}
在ubuntu 12.04 LTS 終端執行:
$gcc -o main main.c -std=c99 # 生成main 可執行程式
$main -d dir # 顯示dir 目錄下所有目錄和檔案
$main # 顯示當前目錄下所有檔案和目錄