代码如下,完成递归遍历目录的功能,输出目录中的文件名和文件类型,使用的是linux的低级IO函数,程序运行时发生段错误,不知道是为什么。
- C/C++ code
void listfiletype(char *name) { DIR *dp=opendir(name); dirent *drp; struct stat buf;//取得文件的元信息。 while((drp=readdir(dp))!=NULL) { lstat(drp->d_name,&buf);//以下if-else判断文件类型。reg普通文件,dir目录。 if(S_ISREG(buf.st_mode)) printf("%s:reg\n",drp->d_name); else if(S_ISDIR(buf.st_mode)) { if((strcmp(drp->d_name,".")!=0)&& (strcmp(drp->d_name,"..")!=0))//don't search upper dir and current dir again. { printf("%s:dir\n",drp->d_name); listfiletype(drp->d_name);//递归遍历目录。 } } else if(S_ISCHR(buf.st_mode)) printf("%s:char\n",drp->d_name); else if(S_ISLNK(buf.st_mode)) printf("%s:link\n",drp->d_name); else if(S_ISBLK(buf.st_mode)) printf("%s:block\n",drp->d_name); else if(S_ISFIFO(buf.st_mode)) printf("%s:fifo\n",drp->d_name); else if(S_ISSOCK(buf.st_mode)) printf("%s:socket\n",drp->d_name); else printf("other.\n"); } closedir(dp); }
------解决方案--------------------
- C/C++ code
DIR *dp=opendir(name);