S_ISDIR returns directories and files?
Hello,
I have a program where I am testing to see whether something is a file or directroy using S_ISDIR. Here is my code:
Code:
void Find::get_dir()
{
struct dirent *ep;
struct stat statbuf;
DIR *dp;
dp = opendir(path.c_str());
if(dp == NULL)
throw domain_error("ERROR - " + path + " is not a valid path.");
while((ep = readdir(dp)))
{
stat(ep->d_name, &statbuf);
if(S_ISDIR(statbuf.st_mode))
dir.push_back(ep->d_name);
}
closedir(dp);
sort(dir.begin(), dir.end());
typedef vector<string>::const_iterator iter;
for(iter i = dir.begin(); i != dir.end(); i++)
cout << *i << endl;
}
My output:
Quote:
.
..
.autofsck
.dbus
bin
boot
dev
home
lib
lost+found
media
mnt
opt
proc
sbin
selinux
srv
sys
tmp
usr
var
Are files and directories both considered file types? I want to weed out files like .dbus and .autofsck and only keep directories. Any ideas?
Don't forget to prepend the path.
I'm thinking that what Salem said should be your clue.
Note that you are looking in 'path' (which is a global??), but then you are not prepending path to the file names that you are looking at, so most likely the stat is failing, and you are calling S_ISDIR() on memory garbage, which may or may not have that bit set, but which *will* be the same for all files.
I'd suspect that if you initialized the stat struct to 0 ( memset(&statbuf, 0, sizeof(statbuf)); ) that you would find no files pushed to your vector (which is also global??)
so yeah ... all that is to say
1) call stat with the path prepended:
Code:
char fullpath[1024];
snprintf(fullpath, 1024, "%s/%s", path.c_str(), ep->d_name);
2) check the return of stat to make sure you're doing it right:
Code:
if (stat(fullpath, &statbuf) == 0)
{
// do stuff
}
else
{
printf("Huh, can't find and stat %s\n", fullpath);
}