#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <dirent.h>
int testdir(char *path)
{
struct stat buf;
if(lstat(path,&buf)<0)
{
return 0;
}
if(S_ISDIR(buf.st_mode))
{
return 1; //directory
}
return 0;
}
int directory(char *path)
{
DIR *db;
char filename[128];
struct dirent *p;
db=opendir(path);
if(db==NULL)return 0;
memset(filename,0,128);
while ((p=readdir(db)))
{
if((strcmp(p->d_name,".")==0)||(strcmp(p->d_name,"..")==0))
continue;
else
{
sprintf(filename,"%s/%s",path,p->d_name);
if(testdir(filename))
{
directory(filename);
}
else {
printf("%s/n",filename);
}
}
memset(filename,0,64);
}
closedir(db);
return 0;
}
int main(int argc,char **argv)
{
char *path="./"; //要遍历的目录
if(access(path,F_OK)==0&&testdir(path))
{
printf("is directory/n");
directory(path);
}
else printf("%s not exist/n",path);
}
后来我又找到了另外还有一种方案,这种方案能帮我解决不能打开文件进行操作的疑惑。主要是使用ftw.h里的方法,该头文件意义是 file tree wall文件目录树遍历:先贴上代码:
#include <iostream>
#include <fstream>
using namespace std;
#include <string.h>
#include <ftw.h>
int fn(const char* file, const struct stat* sb, int flag)
{
char line[256] = {0};
int count = 0;
if (flag == FTW_F) { // 如果是文件
cout<<"The File's name : "<<file<<endl;
/*
ifstream file(file);
if (file.isopen()) {
file.getline(line, 100);
cout<<line<<endl;
}
*/
FILE* fp;
fp = fopen(file, "r");
fgets(line, sizeof(line), fp);
fclose(fp);
printf("Line's data######## : %s\n", line);
}else if (flag == FTW_D) { // 如果是子目录(遍历的第一个是根目录)
cout<<"The Directory name : "<<file<<endl;
}
return 0;
}
int main(int argc, char** argv)
{
ftw("home/~", fn, 0);
return 0;
}