当前位置: 技术问答>linux和unix
获取某路径下的所有文件名并保存到数组
来源: 互联网 发布时间:2016-06-23
本文导语: 请问LINUX下如何将一个目录下的所有文件名都取出来并依此放到一个字符串数组中?用C语言实现 谢谢各位大侠指教。。。 | #include #include char ** dirGetInfo(const c...
请问LINUX下如何将一个目录下的所有文件名都取出来并依此放到一个字符串数组中?用C语言实现
谢谢各位大侠指教。。。
谢谢各位大侠指教。。。
|
#include
#include
char ** dirGetInfo(const char *pathname)
{
char ** filenames;
DIR * dir;
struct dirent * ent;
int n = 0;
filenames = (char **)malloc(sizeof(char*));
filenames[0]=NULL;
dir = opendir(pathname);
if (!dir) return filenames;
while ((ent = readdir(dir))) {
filenames = (char**)realloc(filenames,sizeof(char*)*(n+1));
filenames[n] = strdup(ent->d_name);
n++;
}
closedir(dir);
filenames = (char **)realloc(filenames,sizeof(char*)*(n+1));
filenames[n] = NULL;
return filenames;
}
#include
char ** dirGetInfo(const char *pathname)
{
char ** filenames;
DIR * dir;
struct dirent * ent;
int n = 0;
filenames = (char **)malloc(sizeof(char*));
filenames[0]=NULL;
dir = opendir(pathname);
if (!dir) return filenames;
while ((ent = readdir(dir))) {
filenames = (char**)realloc(filenames,sizeof(char*)*(n+1));
filenames[n] = strdup(ent->d_name);
n++;
}
closedir(dir);
filenames = (char **)realloc(filenames,sizeof(char*)*(n+1));
filenames[n] = NULL;
return filenames;
}