2011-09-29 159 views
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); 
} 

代码在dir和文件中没有区分。我错过了什么吗?我无法使用Boost或任何其他STL。只有C Posix支持的文件。需要知道我是错的。C++中的stat&S_IFREG

更新代码,每回答

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;} 

    } 
+0

考虑使用'S_ISREG(buff.st_mode)'和'S_ISDIR(buff.st_mode)'。不是说它影响'_unchecked'stat()'_'问题。 –

回答

2

我怀疑stat实际上失败,ENOENT(没有这样的文件),因此buff不包含任何有用的东西。

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

您可能想连接fl, "/", d_name。但首先,请检查stat返回的值。

+0

cout <<" "< d_name <<“”<<(buff.st_mode&S_IFDIR)<<“”<< buff.st_mode << endl; \t \t表明这一点: .. 16384 16833 DIR1 16384 16833 DIR2 16384 16833 DIR3 16384 16833 文件1 16384 16833 文件2 16384 16833 – typedefcoder2

+1

@ typedef1尝试通过清点'stat' :-) – cnicutar

+0

它返回的值 - 1在所有情况下..除第一个以外,它是0. – typedefcoder2