一段可以在UNIX下,读取当前目录下所有文件(包括子目录中的文件)的文件名的程序

#include<unistd.h>
#include<dirent.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

char** list(char* dir,int* len)
{
 struct dirent** namelist;
 char **ret=NULL,**sret=NULL;
 int n,rindex,lindex; //index of ret and index of namelist
 struct stat buf;
 int slen=0; //store the number of files in the sub-directory
 char path[1024];
 int i;

 n = scandir(dir, &namelist, 0, alphasort); //number of items in namelist
           if (n < 0)
               printf("scandir failed/n");
           else
     {
      n-=2; //ignore dot and dot-dot
    
      if(n<=0)
      {
       *len=0;
       return ret;
      }
    
      rindex=n-1;
               lindex=n+1;
      n+=2;
      *len=rindex+1;

      ret=(char**)malloc((*len)*sizeof(char*)); 

      for(;rindex>=0;lindex--)
      {
       if(strcmp(namelist[lindex]->d_name,".")==0 || strcmp(namelist[lindex]->d_name,"..")==0)
       {
        continue;
       }
     
       sprintf(path,"%s/%s",dir,namelist[lindex]->d_name);
     //  printf("%s/n",path);
       if(stat(path,&buf)<0)
       {
        printf("failed to acquire the state of the file./n");
        exit(1);
       }

       if(S_ISDIR(buf.st_mode))
       {
        ret[rindex]=strdup("");
        rindex--;
        sret=list(path,&slen);
        ret=(char**)realloc(ret,(*len+slen)*sizeof(char*));
        for(i=0;i<slen;i++)
        {
         ret[*len]=sret[i];
         (*len)++;
        }
        free(sret);
       }
       else
       {
        ret[rindex]=strdup(namelist[lindex]->d_name);
        rindex--;
       }
      }
   

      while(n--) //frees memory blocks
      {
                   free(namelist[n]);
               }
               free(namelist);

      return ret;
     }
 return ret;
}

int ccmp(char** a,char** b)
{
 return strcmp(*a,*b);
}

int main()
{
 int len=0; //sum of file names
 char **fnames;

 fnames=list(".",&len);
 printf("-------------------------------/nlistn: %d/n-------------------------------/n",len);
 qsort(fnames,len,sizeof(char*),ccmp); //给文件名按字母排序
  
 while(len--) //free all allocated memory blocks
 {
  printf("%s/n",fnames[len]);
  free(fnames[len]);
 }
 free(fnames);
}

你可能感兴趣的:(一段可以在UNIX下,读取当前目录下所有文件(包括子目录中的文件)的文件名的程序)