C语言中,如何编写指定文件夹读取所有文件的函数

C语言中,如何编写指定文件夹读取所有文件的函数,第1张

可以用rmdir

不过

限制是

文件夹必须是空的

如果文件仿颂悄夹非空

需要遍历递归调用remove和rmdir删除所有文件和子文樱笑件夹。

事备渣实上

系统命令的rm

-r

也是rmdir和remove

递归的。

1、可以利用getenv函数来实现。

在Linux系统中,home目录的定义是通过系统环境变量中的HOME变量值来确定的,在shell下可以通过

echo $HOME来查看。

而在C语言中,库函数getenv可以用作获取环差枣境变量值。该函数位于stdlib.h, 原型为

char *getenv(char *name)

功能为获取名字为name的环境变量字符串。

所以,下面代码就可以获取到home目录名了:

2、镇埋例程虚旅拆:

char *home

home = getenv("HOME")

printf("the home path is %s\n", home)

//获取指定目录下的所有文件列表 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

}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/tougao/12248661.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-22
下一篇 2023-05-22

发表评论

登录后才能评论

评论列表(0条)

保存