Linux C遍历文件夹

0x01:首先讲一讲遍历文件夹必须要知道的一个结构体struct dirent{};

struct dirent{
			ino_t d_ino; /* inode number */
			off_t d_off; /* offset to next dirent */
			unsigned short d_reclen; /* length of record */
			unsigned char d_tpye; /*type of file;not support by all file system tpyes */
			char d_name[256]; /*file name */
}

0x2:具体用法见如下代码query.c

#include <stdio.h>
#include <dirent.h>

int main(int argc, char **argv)
{
  DIR *pDir = NULL;
  struct dirent * pEnt = NULL;
  unsigned int cnt = 0;

    if (argc != 2)
	{
	 printf("Please input directory name after %s\n", argv[0]);
	 return -1;
	}
	pDir = opendir(argv[1]);
	 if (NULL == pDir)
	  {
	    perror("opendir failed!\n");
	    return -1;
          }

    while (1)
    {
      pEnt = readdir(pDir);
      if(pEnt != NULL)
    {
     // 还有子文件,在此处理子文件
     printf("name:[%s] ,", pEnt->d_name);
     cnt++;
     if (pEnt->d_type == DT_REG)
      {
        printf("普通文件\n");
      }
     else
     {
        printf("非普通文件\n");
     }
    }
     else //没有子文件,跳出循环
     {
     break;
     }
     };
	printf("总文件数为:%d\n", cnt);
	closedir(pDir);
	return 0;
}

效果如下:

curtis@curtis-virtual-machine:~/Desktop/query_dir$ ./a.out /home/
name:[..] ,不是普通文件
name:[curtis] ,不是普通文件
name:[.] ,不是普通文件
总文件数为:3
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值