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

相关函数是
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("--------------------------------------------------\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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值