Linux下面用c语言遍历目录opendir -> readdir -> closedir

这是自己写的一个在Linux下面用c语言遍历目录的程序
LINUX下历遍目录的方法一般是这样的
打开目录  读取  关闭目录
相关函数是
opendir -> readdir -> closedir
可以分别通过man opendir  , man readdir ,man closedir 在linux下面去查询函数用法等.

#include
#include
DIR *opendir(const char *dirname);


#include
struct dirent *readdir(DIR *dirp);

#include
#include
int closedir(DIR *dirp);
当然dirend的结构可以在man readdir中找到
 struct dirent {
               ino_t          d_ino;       /* inode number */
               off_t          d_off;       /* offset to the next dirent */
               unsigned short d_reclen;    /* length of this record */
               unsigned char  d_type;      /* type of file; not supported
                                              by all file system types */
               char           d_name[256]; /* filename */
           };

所以根据这些可以得到代码如下,运行格式为  ./xx     //path 为目录路径
#include
#include
#include
#include
#include
#include

#include

#define MAX_LEN 512
static char* fullpath;
static int dopath();

int main(int argc,char* argv[]){
 printf("--------------------------------------------------\n");
 fullpath=(char *)malloc(MAX_LEN);
 strcpy(fullpath,argv[1]);
 printf("fullpath is %s\n",fullpath);
 dopath();
 int ret;
 
 
 return 0;
}
static int dopath(){
 struct stat statbuf;
 DIR *dir;
 struct dirent *dirp;
 if(lstat(fullpath,&statbuf)<0){
  //if get statbuf failed
  printf("maybe the fullpath error !!");
  return -1;
 }
 //has got statbuf

 printf("S_ISDIR(statbuf.st_mode) is %d\n",S_ISDIR(statbuf.st_mode));
 //when S_ISDIR()==1 it is a dir   when ==0 maybe it is a file
 if(S_ISDIR(statbuf.st_mode)==0){
  printf("it is not a dir ,maybe it's a file !!"); 
  return 0;
 }
 dir = opendir(fullpath);

 if( dir ==NULL){
  printf("can not read dir\n");
  return 0;
 }
 dirp = readdir(dir);
 while(dirp){
  dirp = readdir(dir);
  printf("inode: %d   d_reclen: %d  name: %s\n",dirp->d_ino,dirp-

>d_reclen,dirp->d_name);
 }
 closedir(dir);
 
 return 0;
}

 

你可能感兴趣的:(c)