0
void fun1(char *fl){
//flNamep : stores the path of our directory
DIR *dip;   
struct dirent *dit;
dip = opendir(fl);
if (dip==NULL) {cerr<<"Error\n";exit(-1);}  

while ((dit=readdir(dip)))
 {  
    string trun = (dit->d_name);
    struct stat buff;       
    stat(dit->d_name, &buff); 

    if  (((buff.st_mode & S_IFREG)==S_IFREG)) 
        {cout<<"File"<<endl;}
    else if (((buff.st_mode & S_IFDIR)==S_IFDIR)) 
        {cout<<"Dir"<<endl;} 
     }
closedir(dip);
}

Code does not differentiate in dir and files. Am i missing something? I can not use Boost or any other STL. only C Posix Supported files. Need to know were i am wrong.

Updated code as per answer

    DIR *dip;   
struct dirent *dit;
dip = opendir(flNamep);
if (dip==NULL) {cerr<<"Err\n";exit(-1);}                            

while ((dit=readdir(dip)))
 {  
    string trun = (dit->d_name);
    string fullpath = flNamep;
    fullpath+='/';
    fullpath+=trun;

    if((trun==".") || (trun=="..")) {cout<<"";}         
    else
    {       
    struct stat buff;               

    stat(dit->d_name, &buff);       
        if (((buff.st_mode & S_IFDIR)==S_IFDIR)) 
        {cout<<"Dir"<<endl;} 
        else
        {cout<<"File"<<endl;}

    }
1
  • Consider using S_ISREG(buff.st_mode) and S_ISDIR(buff.st_mode). Not that it affects the 'unchecked stat()' problem. Sep 29, 2011 at 22:36

1 Answer 1

2

I suspect that the stat actually fails with ENOENT (no such file) so buff doesn't contain anything useful.

stat(dit->d_name, &buff); /* dirent.d_name is just the name, not the full path */

You probably want to concatenate fl, "/", d_name. But first of all, check the value returned by stat.

9
  • cout<<" "<<dit->d_name<<" "<<(buff.st_mode & S_IFDIR) << " " <<buff.st_mode<< endl; shows this: .. 16384 16833 dir1 16384 16833 dir2 16384 16833 dir3 16384 16833 file1 16384 16833 file2 16384 16833 Sep 29, 2011 at 20:05
  • 1
    @typedef1 Try to cout the value returned by stat :-)
    – cnicutar
    Sep 29, 2011 at 20:06
  • it is -1 in all Cases .. except first where it is 0. Sep 29, 2011 at 20:11
  • @typedef1 Which means you have to prefix the filename with the path.
    – cnicutar
    Sep 29, 2011 at 20:12
  • 1
    str::string provides a method c_str(); use it. Sep 29, 2011 at 22:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.