How to find Directory in Linux using c? -
i'm making c program in linux user enter directory name found. following code have written not getting correct output. i'm searching through directories till found directory.
i'm beginner.
#include<unistd.h> #include<dirent.h> #include<stdio.h> #include<stdlib.h> #include<string.h> #include<sys/stat.h> #include<errno.h> void finddir(char *dir, char *name) { dir *dp; struct dirent *entry; struct stat statbuf; if((dp = opendir(dir)) == null) { printf("\ncan not open directory: %s", name); printf("\ndescription: %s", strerror(errno)); return; } chdir(dir); while(( entry = readdir(dp)) != null) { lstat( entry->d_name, &statbuf); if(s_isdir( statbuf.st_mode)) { if( strcmp(name,entry->d_name) == 0) { printf("dir found"); return; } finddir(entry->d_name, name); } } chdir(".."); closedir(dp); } void main(int argc, char *argv[]) { if( argc != 2 ) { printf("error"); } else { finddir("/home", argv[1]); } }
please help!! follwing output while giving documents argument. program goes infinite , repeteadly following output. little of output.
can not open directory: documents
description: many open files
can not open directory: documents
description: many open files
can not open directory: documents
description: many open filesdir found
i took quick @ this. here advice.
when debugging, either single-step in debugger or @ least put print statements see happening. put in
printf()
in loop walks directories, , found right away trying visit..
directory, leaves/home
, loops forever.so, in loop, before else, test see if
entry->d_name
"."
or".."
, , if so, skip directory entry (you can usecontinue
keyword).make sure call
closedir(dp);
before function returns. example, when code prints messagecan not open directory:
, function returns without closing directory. way, should printentry->d_name
in error message, notname
.
the error too many open files
because loop following ..
never stop, , finds plenty of directories cannot open, code not calling closedir()
on error exit means more , more directories left open.
- your program keep on going after finds target directory! print message keep on going. can modify function
finddir()
return code saying whether found target or not, , make program stop in case.
Comments
Post a Comment