本文介绍了统计& S_IFREG在C ++中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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支持的文件。需要知道我错了。

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.

根据回答更新的代码

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

    }


推荐答案

我怀疑 stat 实际上失败了 ENOENT )因此 buff 不包含任何有用的内容。

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 */

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

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

这篇关于统计&amp; S_IFREG在C ++中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 20:11