C语言读取文件夹一级子目录的指定类型文件

参考链接:

C语言读取指定文件夹下的所有文件(各种信息)_c语言读取文件夹下的所有文件-CSDN博客

参考以上文案,做成了几个函数,用于读取任意文件夹下的指定后缀的文件。

cpp 复制代码
#include <stdio.h>
#include <io.h>
#include <direct.h>
void loadfile_scanf(char *dirname,char* next,char* kind,char **msg)
{
	//文件存储信息结构体
	struct _finddata_t fileinfo;
	//保存文件句柄
	long fHandle;
	//文件数记录器
	char dirpath[100];
	strcpy(dirpath,dirname);
	if(access(dirpath,0)==-1)								// 检查文件夹是否存在,不存在为 -1
	{
		mkdir(dirpath);
		return;
	}
	else
	{
		int i = 0;																	// 记录文件数量
		char kindpath[100];
		strcpy(kindpath,dirpath);
		strcat(kindpath,next);
		strcat(kindpath,kind);
		if( (fHandle=_findfirst( kindpath, &fileinfo )) == -1L ) 					// *是通配符,默认在当前文件夹内查找文件,这里查找 .png 文件
		{
			printf( "当前目录: %s 下没有 txt 文件\n",dirname);
			return ;
		}
		else
		{
			FILE *fp;
			char test[100]="";														// 存储读取到的数据
			char path[100];
			do
			{
				i ++;
				printf( "找到文件:%s,文件大小:%d bit\n", fileinfo.name,fileinfo.size);
				strcpy(path,dirname);
				strcat(path,next);
				strcat(path,fileinfo.name);
				fp=fopen(path,"r");
				fscanf(fp,"%s\n",test);
				printf("已接收内容:%s\n",test);
				fclose(fp);
				strcpy(msg[i],test);
			}
			while( _findnext(fHandle,&fileinfo)==0);
		}
		//关闭文件
		_findclose( fHandle );

		printf("文件数量:%d\n",i);
	}
}
void showmsg(char** msg,int num)
{
	for(int i=1; i<num; i++)
		if(strcmp(msg[i],"")!=0)
			printf("show num:%d : %s\n",i,msg[i]);
}
void flushmsg(char** msg,int num)
{
	for(int i=0; i<num; i++)
	{
		strcpy(msg[i],"");
	}
}
void loadfile(char **msg)
{
	char brick[100]="birck_6_family";
	char ground[100]="ground_7_family";
	char change[100]="change_8_family";
	char trick[100]="trick_9_family";
	char next[100]="./";
	char png[100]="*.txt";
	loadfile_scanf(brick,next,png,msg);
	showmsg(msg,10);
	flushmsg(msg,10);
	loadfile_scanf(ground,next,png,msg);
	showmsg(msg,10);
	flushmsg(msg,10);
	loadfile_scanf(change,next,png,msg);
	showmsg(msg,10);
	flushmsg(msg,10);
	loadfile_scanf(trick,next,png,msg);
	showmsg(msg,10);
	flushmsg(msg,10);
}
int main()
{
	int num=10;
	char **msg;
	msg=new char* [num];
	for(int i=0; i<num; i++)
	{
		msg[i]=new char[100];
		strcpy(msg[i],"");
	}
	loadfile(msg);
	return 0;
}
相关推荐
dme.12 分钟前
Javascript之DOM操作
开发语言·javascript·爬虫·python·ecmascript
teeeeeeemo17 分钟前
回调函数 vs Promise vs async/await区别
开发语言·前端·javascript·笔记
加油吧zkf22 分钟前
AI大模型如何重塑软件开发流程?——结合目标检测的深度实践与代码示例
开发语言·图像处理·人工智能·python·yolo
学不动CV了26 分钟前
数据结构---链表结构体、指针深入理解(三)
c语言·arm开发·数据结构·stm32·单片机·链表
ejinxian37 分钟前
PHP 超文本预处理器 发布 8.5 版本
开发语言·php
软件黑马王子1 小时前
C#系统学习第八章——字符串
开发语言·学习·c#
阿蒙Amon1 小时前
C#读写文件:多种方式详解
开发语言·数据库·c#
Da_秀1 小时前
软件工程中耦合度
开发语言·后端·架构·软件工程
Fireworkitte1 小时前
Java 中导出包含多个 Sheet 的 Excel 文件
java·开发语言·excel
运器1233 小时前
【一起来学AI大模型】算法核心:数组/哈希表/树/排序/动态规划(LeetCode精练)
开发语言·人工智能·python·算法·ai·散列表·ai编程