纯C,拿取文件夹的所有文件,并套出列表
//构造体
typedef struct FilesArrayStruct {
char** fileArray;
int arraySize;
} FilesArrayStruct_t;
//函数
FilesArrayStruct_t getFilesArray(const char *dirName)
{
FilesArrayStruct_t FilesArrayStruct_p;
FilesArrayStruct_p.arraySize=0;
DIR *dirp;
struct dirent *dp;
dirp = opendir(dirName);
while ((dp = readdir(dirp)) != NULL) {
if(strcmp(dp->d_name,"..")==0)continue;
if(strcmp(dp->d_name,".")==0)continue;
FilesArrayStruct_p.arraySize++;
}
(void) closedir(dirp);
if (FilesArrayStruct_p.arraySize > 0)
{
FilesArrayStruct_p.fileArray=(char**)malloc(sizeof(char*)*FilesArrayStruct_p.arraySize) ;
for(int i=0; i<FilesArrayStruct_p.arraySize; i++)
FilesArrayStruct_p.fileArray[i]=(char*)malloc(256);
}
int i=0;
dirp = opendir(dirName);
while ((dp = readdir(dirp)) != NULL) {
if(strcmp(dp->d_name,"..")==0)continue;
if(strcmp(dp->d_name,".")==0)continue;
FilesArrayStruct_p.fileArray[i]=(char*)malloc(strlen(dp->d_name)+1) ;
FilesArrayStruct_p.fileArray[i]=dp->d_name;
i++;
}
(void) closedir(dirp);
return FilesArrayStruct_p;
}
//测试
int test6()
{
FilesArrayStruct_t FilesArrayStruct_p= getFilesArray("/home/test/CWork/Json");
for(int i=0;i<FilesArrayStruct_p.arraySize;i++)
{
printf("FilesArrayStruct_p.fileArray[%d]:%s\n",i,FilesArrayStruct_p.fileArray[i]);
}
return 0;
}