c语言获取文件目录,C语言 获取指定目录下的文件列表

//获取指定目录下的所有文件列表 author:wangchangshaui jlu

char** getFileNameArray(const char *path, int* fileCount)

{

int count = 0;

char **fileNameList = NULL;

struct dirent* ent = NULL;

DIR *pDir;

char dir[512];

struct stat statbuf;

//打开目录

if ((pDir = opendir(path)) == NULL)

{

myLog("Cannot open directory:%s\n", path);

return NULL;

}

//读取目录

while ((ent = readdir(pDir)) != NULL)

{ //统计当前文件夹下有多少文件(不包括文件夹)

//得到读取文件的绝对路径名

snprintf(dir, 512, "%s/%s", path, ent->d_name);

//得到文件信息

lstat(dir, &statbuf);

//判断是目录还是文件

if (!S_ISDIR(statbuf.st_mode))

{

count++;

}

} //while

//关闭目录

closedir(pDir);

//myLog("共%d个文件\n", count);

//开辟字符指针数组,用于下一步的开辟容纳文件名字符串的空间

if ((fileNameList = (char**) myMalloc(sizeof(char*) * count)) == NULL)

{

myLog("Malloc heap failed!\n");

return NULL;

}

//打开目录

if ((pDir = opendir(path)) == NULL)

{

myLog("Cannot open directory:%s\n", path);

return NULL;

}

//读取目录

int i;

for (i = 0; (ent = readdir(pDir)) != NULL && i < count;)

{

if (strlen(ent->d_name) <= 0)

{

continue;

}

//得到读取文件的绝对路径名

snprintf(dir, 512, "%s/%s", path, ent->d_name);

//得到文件信息

lstat(dir, &statbuf);

//判断是目录还是文件

if (!S_ISDIR(statbuf.st_mode))

{

if ((fileNameList[i] = (char*) myMalloc(strlen(ent->d_name) + 1))

== NULL)

{

myLog("Malloc heap failed!\n");

return NULL;

}

memset(fileNameList[i], 0, strlen(ent->d_name) + 1);

strcpy(fileNameList[i], ent->d_name);

myLog("第%d个文件:%s\n", i, ent->d_name);

i++;

}

} //for

//关闭目录

closedir(pDir);

*fileCount = count;

return fileNameList;

}

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值