linux環境下掃描文件

1 篇文章 0 订阅
#include <fcntl.h>         //open()函數
#include <unistd.h>
#include <stdio.h>
#include <dirent.h>        //提供目錄流操作
#include <string.h>
#include <sys/stat.h>      //提供屬性操作函數
#include <sys/types.h>     //提供mode_t類型
#include <stdlib.h>
/**
 * 該函數的作用是遍歷目錄
 * @dir 目錄
 * @dePth 子目錄前增加空格的數量
 *
 *
 * eg:  /home
 *          ./xiaoming
 *                   ./Downloads
 *                   ./Desktop
 *                   ./6140
 *          ./root
 *1. opendir("/home")   返回子目錄流 ( DIR* ) ./xiaoming 和 ./root
 *2. chdir("/home")     切換到/home目錄
 *3. readdir(DIR*)      返回指定目錄的下一級信息( dirent* ) 如 ./Downloads ./Desktop
 *4. lstat("/home/xiaoming/Downloads", &statbuf); 獲取指定目錄的屬性
 *5. chdir("..");       回到上一級目錄,對應步驟2
 *6. closedir("/home")  關閉目錄
 */
void scanDir(char* dir, int dePth) {
	DIR* dp;             //定義子目錄流指針
	struct dirent* entry;//定義dirent結構體指針保存後續目錄
	struct stat statbuf; //定義statbuf結構體保存文件屬性
	if ((dp = opendir(dir)) == NULL) { //打開目錄,獲得子目錄流指針,判斷操作是否成功
		puts("無法打開該目錄");
		return;
	}

	chdir(dir);   //切換到當前目錄去

	while ((entry = readdir(dp)) != NULL) {  //獲得下一級目錄信息,如果爲結束則循環

		lstat(entry->d_name, &statbuf); //獲取下一級成員屬性

		if (S_IFDIR & statbuf.st_mode) {   //判斷下一級成員是否是目錄
			if (strcmp(".", entry->d_name) == 0
					|| strcmp("..", entry->d_name) == 0) {
				//如果獲得的成員符號是 "." 或者 "..",則跳過本次循環
				continue;
			}
			printf("%*s%s/\n",dePth,"",entry->d_name);

			scanDir(entry->d_name,dePth+4);   //遞歸,掃描下一級目錄
		}else{

			printf("%*s%s/\n",dePth,"",entry->d_name); //輸出屬性不是目錄的成員
		}
	}

	chdir("..");   //回到上一級目錄

	closedir(dp);  //關閉子目錄
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值