用递归方法输出目录下所有的文件名

# !/bin/bash
function echo_name()
{
	#shell会执行反引号中的内容(命令)
	for file in `ls $1`
	do
		if [ -d $1'/'$file ]
		then
			echo_name $1'/'$file
		else
			echo $1'/'$file 
		fi
	done
}
echo_name $1

查询/app/tomcat/bin/config下的所有文件名称,若程序文件名为printfiles.sh

则在程序目录下运行:./printfiles.sh /app/tomcat/bin/config

好的,下面是使用递归方法实现输出指定目录下所有子目录文件名的 C 语言代码示例: ```c #include <stdio.h> #include <dirent.h> #include <sys/stat.h> #include <string.h> void print_files(char *dir_path) { DIR *dir; struct dirent *entry; struct stat statbuf; char file_path[256]; if ((dir = opendir(dir_path)) == NULL) { fprintf(stderr, "Error: cannot open directory %s\n", dir_path); return; } while ((entry = readdir(dir)) != NULL) { sprintf(file_path, "%s/%s", dir_path, entry->d_name); if (lstat(file_path, &statbuf) < 0) { fprintf(stderr, "Error: cannot stat file %s\n", file_path); continue; } if (S_ISDIR(statbuf.st_mode)) { if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { continue; } printf("directory: %s\n", file_path); print_files(file_path); } else { printf("file: %s\n", file_path); } } closedir(dir); } int main(int argc, char *argv[]) { if (argc < 2) { fprintf(stderr, "Usage: %s <directory>\n", argv[0]); return 1; } print_files(argv[1]); return 0; } ``` 在这个示例中,我们使用 `opendir()` 函数打开指定目录,然后使用 `readdir()` 函数遍历目录中的所有文件和子目录。对于每个文件或子目录,我们使用 `lstat()` 函数获取其详细属性信息,判断其是否为子目录。如果是子目录,则递归调用 `print_files()` 函数,继续遍历该子目录下的所有文件和子目录;如果是普通文件,则直接输出文件路径。 需要注意的是,在递归调用 `print_files()` 函数时,需要传入子目录的路径,而不是子目录文件名。另外,为了防止无限递归,我们需要排除子目录中的 `.` 和 `..` 文件。 最后,在 `main()` 函数中,我们检查是否传入了指定目录的路径参数,如果没有则输出使用方法。然后调用 `print_files()` 函数,传入指定目录的路径即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值