通过用C目录遍历 [英] Traversing through Directories in C
本文介绍了通过用C目录遍历的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图通过目录其路径给出,但下面的程序是不会目录内,滞留在无穷远循环遍历。什么是这个code中的问题:
无效FUNC(字符路径[]);
INT主(INT ARGC,CHAR *的argv)
{
焦炭BUF [255];
GETCWD(BUF,255);
FUNC(BUF);
}无效FUNC(字符路径[])
{
DIR * dirp;
struct stat中的状态;
结构的dirent * direntp; dirp =执行opendir(路径);
CHDIR(路径); 而((direntp = READDIR(dirp))!= NULL)
{
如果(S_ISDIR(states.st_mode))//真不是返回零
{
的printf(%S \\ n,direntp-> d_name);
}
其他
如果((STRCMP(direntp->!d_name,)|| STRCMP(direntp-&gt的帮助。d_name,)))//如果为true retrns为零
{
继续;
}
其他
{
FUNC(direntp-> d_name);
CHDIR();
}
}
}
解决方案
您可以检查是否该节点是目录,而辅助状态
。结构的dirent
有一个名为字段 d_type
,并将其与 DT_DIR
来测试是否是一个目录。
I am trying to traverse through a directory whose path is given but the following program is not going inside the directories and is stuck in infinit loop. What is the problem in this code:
void func(char path[]);
int main(int argc, char *argv)
{
char buf[255];
getcwd(buf,255);
func(buf);
}
void func(char path[])
{
DIR *dirp;
struct stat states;
struct dirent *direntp;
dirp=opendir(path);
chdir(path);
while((direntp=readdir(dirp))!=NULL)
{
if(S_ISDIR(states.st_mode))//true than returns zero
{
printf("%s\n",direntp->d_name);
}
else
if(!(strcmp(direntp->d_name,".")||strcmp(direntp->d_name,"..")))// if true retrns zero
{
continue;
}
else
{
func(direntp->d_name);
chdir("..");
}
}
}
解决方案
You can check whether if the node is directory without an auxiliary states
.struct dirent
has a field called d_type
, AND it with DT_DIR
to test if it is a directory.
这篇关于通过用C目录遍历的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文