开发者

stat & S_IFREG in C++

开发者 https://www.devze.com 2023-04-09 04:21 出处:网络
void fun1(char *fl){ //flNamep : stores the path of our directory DIR *dip; struct dirent *dit; dip = opendir(fl);
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"&l开发者_C百科t;<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;}

    }


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消