用简单的C语言程序遍历文件夹

#include <stdio.h>
#include<io.h>
#include<string.h>

int Function(char *,char *);//文件夹遍历函数
void Connect(char*,char*,char*);//字符串连接函数

void main()
{
	char a[50]="";
	char b[5]="\\*.*";   // *.*代表全部类型的文件,类似的 *.txt则代表txt类型的文件
	printf("输入文件夹位置:");
	scanf("%s",a);    //输入你要遍历的目录
	printf("文件夹中的所有文件如下:\n");
	Function(a,b);   //调用遍历文件夹的函数
}

int Function(char *a,char *b){  //文件夹遍历函数
	char c[100],*p1,*p2;
	p1=c;
	Connect(a,b,p1);
	struct _finddata_t file;
	long fHandle;
	if( (fHandle=_findfirst(c, &file ))==-1L )
	{
		printf( "当前目录下没有文件\n");
		return 0;
	}
	else
		do{
			if (file.attrib & _A_SUBDIR)
				{
					//判断是否为"."当前目录,".."上一层目录
					if ((strcmp(file.name, ".") != 0) && (strcmp(file.name, "..") != 0))
					{
						char newPath[100];
						p2=newPath;
						Connect(a,"\\",p2);//函数执行完成后p2仍指向newPath[0]
						for(int i=0;newPath[i]!='\0';i++){p2++;}//移动指针
						Connect("",file.name,p2);
						Function(newPath,b);//递归调用
					}
				}
			else{
				char b1[50];//用来存放文件的具体位置
				int j=0;
				for(int i=0;a[i]!='\0';i++)
				b1[j++]=a[i];
				b1[j++]='\\';
				for(i=0;file.name[i]!='\0';i++)
					b1[j++]=file.name[i];
				b1[j]='\0';
				printf("%s\n",b1);  
			}
		}while( _findnext(fHandle,&file)==0 );
	_findclose( fHandle );
	return 0;
}

void Connect(char* str1, char* str2, char* p) { //字符串连接函数
	int i = 0;
	for (; *str1 != '\0';) {
		*p = *str1;
		str1++;
		p++;
	}
	for (; *str2 != '\0';) {
		*p = *str2;
		str2++;
		p++;
	}
	*p = '\0';
}

结果示例如下:
在这里插入图片描述
本段代码原理很简单,其中为了使结果呈现的更加具体,我加入了一些printf语句,显得内容有点多。

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值