• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

wchenfeng

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

遍历目录下的所有文件(文件)

前情提要

文件内容结构

 

本地文件夹

 

代码实现

#include <stdio.h>
#include<io.h>
#include<string.h>
#define MaxSize 100//这里是目录底下最多的文件数量设置,文件数量设置要多余等于实际情况,不然不能全部出来
int Function(char *,char *);//文件夹遍历函数
void Connect(char*,char*,char*);//字符串连接函数

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

int Function(char *a,char *b){  //文件夹遍历函数
	char c[100],*p1,*p2;
	int i;
	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[MaxSize];//用来存放文件的具体位置,注意需要大量的空间
				int j=0;
				for(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;
	while(*str1 != '\0')
	{
		*p = *str1;
		str1++;p++;
	}
	while(*str2!='\0')
	{
		*p = *str2;	
		str2++;p++;
	}
	*p = '\0';//收尾结束
}

输出

 

posted on 2022-04-12 20:02  王陈锋  阅读(244)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3