C语言遍历文件和目录

本文介绍了一个使用C语言编写的目录遍历程序,该程序能够递归地列出指定路径下的所有子目录和文件,并统计目录和文件的数量。程序利用了标准C库中的多个头文件,包括用于文件系统操作的 dirent.h 和 sys/stat.h,展示了如何通过 opendir 和 readdir 函数读取目录内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>

#define MAX_PATH_LENGTH		512
#define MAX_FILE_EXTENSION	9

unsigned long visit_dirs = 0;
unsigned long visit_files = 0;

void listdir(char *path){
	DIR 		*ptr_dir;
	struct dirent 	*dir_entry;
	int 		i = 0;
	char		*child_path;
	char		*file_path;

	child_path = (char*)malloc(sizeof(char)*MAX_PATH_LENGTH);
	if(child_path == NULL){
		printf("allocate memory for path failed.\n");
		return;
	}
	memset(child_path, 0, sizeof(char)*MAX_PATH_LENGTH);

	file_path = (char*)malloc(sizeof(char)*MAX_PATH_LENGTH);
	if(file_path == NULL){
		printf("allocate memory for file path failed.\n");
		free(child_path);
		child_path = NULL;
		return;
	}
	memset(file_path, 0, sizeof(char)*MAX_PATH_LENGTH);

	ptr_dir = opendir(path);
	while((dir_entry = readdir(ptr_dir)) != NULL){
		if(dir_entry->d_type & DT_DIR){
			if(strcmp(dir_entry->d_name,".") == 0 ||
			   strcmp(dir_entry->d_name,"..") == 0){
				continue;
			}

			sprintf(child_path, "%s/%s", path, dir_entry->d_name);
			printf("[DIR]%s\n", child_path);

			visit_dirs++;

			listdir(child_path);
		}

		if(dir_entry->d_type & DT_REG){
			sprintf(file_path, "%s/%s", path, dir_entry->d_name);
			printf("[FILE]%s\n", file_path);
			visit_files++;
		}
	}

	free(child_path);
	child_path = NULL;

	free(file_path);
	file_path = NULL;
}

int main(int argc, char* argv[]){
	if(argc == 2){
		listdir(argv[1]);
		printf("Total DIR: %ld, Total FILE: %ld\n", visit_dirs, visit_files);
	}else{
		printf("Usage: listdir <dir>\n");
		return;
	}
	
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值