- Shell语言
此题采用命令行+bat(windows批处理文件)实现查询,主要方法有两个,第一个是使用dir命令加上find命令对特定目录下各种类型文件数目进行统计;第二个是使用for语句对特定目录下文件进行遍历并进行统计,具体如下:
编译环境:
- dir语句加find语句实现
@echo off
set /p p1=echo.where do you want to find?
set /p p2=echo.which type do you want to find?
dir /s /b /a-d %p1% | find /c ".%p2%"
pause
思路:set/p函数实现外部设备写操作,输入需要查找的目录的地址以及需要查找的文件后缀名,接着用dir/s/b语句实现对目标地址目录的遍历,接着用find语句,将dir语句读出的文件名进行查找并对具有目标后缀名的文件进行计数最后输出。
步骤:打开命令行窗口,将bat文件拖入后即可运行脚本,接着依次输入目标目录的地址和目标文件后缀名,回车键入即可得到目标目录下特定后缀名文件个数。
样例及运行截图:
(D:\test目录下具有3个pdf文件)
2.for语句实现
@echo off
set /p add=- ^where do you want to find
set /p type=- ^which type of doc do you want to find
set cnt=0
for /r %add% %%i in (.%type%) do @echo "%%i" && set /a cnt+=1
@echo %cnt%
pause
思路:同样是用set/p函数实现输入,这次定义一个计数变量cnt,并用for/r语句对目标目录地址的文件进行递归遍历,并对拥有目标后缀名的文件进行名称输出并计数,最后对数量进行输出
步骤:打开命令行窗口,将bat文件拖入后即可运行脚本,接着依次输入目标目录的地址和目标文件后缀名,回车键入即可得到目标目录下特定后缀名文件个数。
样例及运行截图:
(D:\test目录下具有3个pdf文件,名字分别为3,4,5)
- C/C++语言
运行环境:
代码:
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string.h>
#include <fstream>
#include <cstring>
#include <io.h>
extern int num = 0;
using namespace std;
void findFile(const char* path, const char* format);
int main()
{
findFile("D:\\test", ".pdf");
printf("%d", num);
return 0;
}
void findFile(const char* path, const char* format)
{
char newpath[200];
strcpy(newpath, path);
strcat(newpath, "\\*.*");
int handle;
_finddata_t findData;
handle = _findfirst(newpath, &findData);
if (handle == -1) // 检查是否成功
return;
while (_findnext(handle, &findData) == 0) {
if (findData.attrib & _A_SUBDIR) {
if (strcmp(findData.name, ".") == 0 || strcmp(findData.name, "..") == 0)
continue;
strcpy(newpath, path);
strcat(newpath, "\\");
strcat(newpath, findData.name);
findFile(newpath, format);
}
else {
if (strstr(findData.name, format)) { //判断是不是txt文件
cout << findData.name << "\t" << path << "\n";
num += 1;
}
}
}
_findclose(handle);
}
思路:主要是遍历函数,目标是对目标目录下的所有文件名进行遍历进而找到含有目标后缀名的文件,将它们的名称,地址路径输出并对他们进行计数最后对总数进行输出。
步骤:在代码中的main函数中将目标目录和目标文件后缀名写入,接着ctrl+f5运行后打开GUI窗口便会依次出现目标文件的名字,地址以及最后它们的出现次数。
样例及运行截图:
(D:\test目录下具有3个pdf文件,名字分别为3,4,5)