腾讯面试:Linux下如何扫描目录

来源:互联网 发布:党规党纪面前知敬畏 编辑:程序博客网 时间:2024/06/06 00:30

问题:在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;}
原创粉丝点击