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支持的文件。需要知道我错了。
根据答案更新了代码
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 :(得分:2)
我怀疑stat
实际上失败了ENOENT
(没有这样的文件),因此buff
不包含任何有用的内容。
stat(dit->d_name, &buff); /* dirent.d_name is just the name, not the full path */
您可能想要连接fl, "/", d_name
。但首先,请检查stat
返回的值。