program to list recursively all of the subdirectories for a given directory. It works for the 1st few dirs but then starts listing regular files
#include %26lt;stdio.h%26gt;
#include %26lt;sys/stat.h%26gt;
#include %26lt;sys/types.h%26gt;
#include %26lt;dirent.h%26gt;
#include %26lt;string.h%26gt;
main(argc,argv) int argc; char *argv[];
{
printf("%s\n", argv[1]);
dir_list(argv[1]);
}
dir_list(char curr_dir[])
{
DIR *dirp = opendir(curr_dir);
struct dirent *direntp;
char dir_name[1024];
while ((direntp = readdir(dirp)) != NULL)
{
strcpy(dir_name, direntp-%26gt;d_name);
if (check_if_dir(direntp-%26gt;d_name))
{
printf("%s\n", dir_name);
if (dir_name[0] == '.' %26amp;%26amp; (strlen(dir_name) ==1 ||
dir_name[1] == '.'));
else
{
dir_list(dir_name);
}
}
}
}
check_if_dir(char dir[])
{
opendir(dir);
struct stat statbuf;
stat(dir, %26amp;statbuf);
return (statbuf.st_mode %26amp; S_IFDIR);
}
C programming project-- what am I doing wrong?
One of the programs in the Chapter 1 of Richard Stevens' book 'Advanced Programming in the UNIX Environment'. Go through that book.
Reply:I did this as a lab in computer science. Big tip: before you check another directory, make sure you close the one you have open. The reason is because every operating system has a finite number of file handles you can open, opening a directory is considered opening a file, and you don't want to run out of file handles and have the program crash. A good order to do this is:
ListDir(char *dirName)
{
// open directory
// list its contents
// close the directory
// call ListDir on each directory
}
Your method to determine if it's a directory looks right, perhaps you have too many files open and you are seeing erratic behavior (I would think it would crash normally)?
plum
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment