入门客AI创业平台(我带你入门,你带我飞行)
博文笔记

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

创建时间:2016-11-07 投稿人: 浏览次数:1338

相关函数是
opendir -> readdir -> closedir
可以分别通过man opendir  , man readdir ,man closedir 在linux下面去查询函数用法等.

seekdir,telldir,scandir


linux shell 遍历目录同样经常使用。

一次opendir -> readdir ,只能遍历当前目录的子目录,不会递归遍历。


#include <sys/types.h>
#include <dirent.h>
DIR *opendir(const char *dirname);


#include <dirent.h>
struct dirent *readdir(DIR *dirp);

#include <sys/types.h>
#include <dirent.h>
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>    //path 为目录路径
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>

#include <unistd.h>

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

int main(int argc,char* argv[]){
 printf("-------------------------------------------------- ");
 fullpath=(char *)malloc(MAX_LEN);
 strcpy(fullpath,argv[1]);
 printf("fullpath is %s ",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 ",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 ");
  return 0;
 }
 dirp = readdir(dir);
 while(dirp){
  dirp = readdir(dir);
  printf("inode: %d   d_reclen: %d  name: %s ",dirp->d_ino,dirp-

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

声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
  • 上一篇:没有了
  • 下一篇:没有了
未上传头像