问题
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("..");
}
}
}
回答1:
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.
回答2:
You're either missing some code or the issue is the fact that you never populate/update states
.
Also have another look at this line:
if(!(strcmp(direntp->d_name,".")||strcmp(direntp->d_name,"..")))
It will never evaluate to a true value as that would require the direntp->d_name
to be equal to .
and ..
at the same time (which is simply impossible). I guess you wanted to check with a &&
here, which would only enter the branch in case your directory name matches either value.
回答3:
In this piece of your code, states
is not initialized before it is used:
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
I think compiler would warn about that, too, so please switch on warning in your compiler (-W -Wall
for gcc), and then heed and fix the warnings.
来源:https://stackoverflow.com/questions/13855932/traversing-through-directories-in-c