Skip to content

Instantly share code, notes, and snippets.

@junjihashimoto
Last active December 21, 2015 21:49
Show Gist options
  • Save junjihashimoto/6371419 to your computer and use it in GitHub Desktop.
Save junjihashimoto/6371419 to your computer and use it in GitHub Desktop.
scandir-sample
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
//#define _SVID_SOURCE
//#define __USE_BSD
#include <dirent.h>
typedef struct Vector{
//public
char** buf;
int len;
//private
int buflen;
} Vector;
int vector_init(Vector* vec);
int vector_free(Vector* vec);
int vector_push(Vector* vec,const char* str);
int vector_set(Vector* vec,int pos,const char* str);
int
vector_init(Vector* vec){
int newbuflen=64;
vec->buf=malloc(sizeof(char*)*newbuflen);
vec->buflen=newbuflen;
vec->len=0;
}
int
vector_free(Vector* vec){
int i;
for(i=0;i<vec->len;i++)
free(vec->buf[i]);
free(vec->buf);
vec->buf=NULL;
}
int
vector_push(Vector* vec,const char* str){
RETRY:
{
int rest=vec->buflen-vec->len;
if(rest>0){
vec->buf[vec->len++]=strdup(str);
}else{
char** newbuf;
int newbuflen=vec->buflen*2;
newbuf=(char**)realloc(vec->buf,sizeof(char*)*newbuflen);
vec->buf=newbuf;
vec->buflen=newbuflen;
goto RETRY;
}
}
return 0;
}
int
vector_set(Vector* vec,int pos,const char* str){
if(vec->buf[pos]!=NULL)
free(vec->buf[pos]);
vec->buf[pos]=strdup(str);
return 0;
}
Vector
scandir_vec(char* dir){
Vector vec;
struct dirent **namelist;
int n;
int i;
vector_init(&vec);
n = scandir(dir, &namelist, 0, alphasort);
if (n < 0)
perror("scandir");
else {
for(i=0;i<n;i++){
vector_push(&vec,(const char*)namelist[i]->d_name);
free(namelist[i]);
}
free(namelist);
}
return vec;
}
void
scanfind(Vector* vec,char* dir){
struct dirent **namelist;
int n;
int i;
n = scandir(dir, &namelist, 0, alphasort);
if (n < 0)
perror("scandir");
else {
for(i=0;i<n;i++){
if(strcmp(namelist[i]->d_name,"..")!=0&&
strcmp(namelist[i]->d_name,".")!=0){
char buf[1024];
snprintf(buf,sizeof(buf),"%s/%s",dir,namelist[i]->d_name);
vector_push(vec,buf);
if(namelist[i]->d_type == DT_DIR){
scanfind(vec,buf);
}
}
free(namelist[i]);
}
free(namelist);
}
}
int
main(void){
Vector vec;
vector_init(&vec);
scanfind(&vec,"/tmp");
int i=0;
for(i=0;i<vec.len;i++)
printf("%s\n",vec.buf[i]);
vector_free(&vec);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment