问题:在linux下,输出某个文件夹下的文件即其子目录,以及子目录下的文件和文件夹。
代码如下:
#include<iostream>
#include<unistd.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<dirent.h>
#include<fcntl.h>
#include<string.h>
/*值得注意的是: struct stat statBuf;
1.如果声明为 struct stat * statBuf,后面用指针方式操作的时候,总是出错。
2.必须使用chdir,否则不在文件所在目录工作的话,S_ISDIR会将文件判定为文件夹而引发错误。
*/
using namespace std;
int printDir(const char * dirPath)
{
DIR * dir;
struct dirent * entry;
struct stat statBuf;
if ((dir=opendir(dirPath))==NULL)
{
cout<<"error when open the directory!"<<endl;
return -1;
}
else
{
chdir(dirPath);
while((entry=readdir(dir))!=NULL)
{
lstat(entry->d_name,&statBuf);
if (S_ISDIR(statBuf.st_mode))
{
if ((strcmp(".",entry->d_name)==0)||(strcmp("..",entry->d_name)==0)) continue;
cout<<"this is a directory"<<entry->d_name<<endl;
printDir(entry->d_name);
}
else cout<<"this is a document"<<entry->d_name<<endl;
}
chdir("..");
closedir(dir);
}
}
int main()
{
printDir(".");
return 0;
}
本文介绍了一段用于在Linux环境下遍历指定文件夹及其子目录中所有文件和文件夹的代码实现,包括如何正确声明和使用结构体以及避免在不同目录下运行时可能出现的问题。
5482

被折叠的 条评论
为什么被折叠?



