// VC下遍历文件夹下所有文件或者特定格式的文件,vs2008下运行OK
-
#include "stdafx.h"
-
#include <stdio.h>
-
#include <iostream>
-
#include <windows.h>
-
#include <string>
-
#include <map>
-
#include <utility>
-
-
using namespace std;
-
-
void fileFind(char* lpPath, map<string, int>& mapFile)
-
{
-
int count = 0;
-
-
char curFind[MAX_PATH];//定义一个char数组存放路径,MAX_PATH为路径最大长度,为260
-
-
strcpy(curFind,lpPath); // 将路径copy到当前的数组
-
strcat(curFind,"*.*"); //在数组后加上*.*,匹配文件和文件夹
-
-
-
WIN32_FIND_DATA fileData; //定义文件的九种属性
-
HANDLE fileHandle = ::FindFirstFile(curFind, &fileData); //获得文件句柄
-
//cout<<fileData.cFileName<<endl;
-
while(::FindNextFile(fileHandle, &fileData)) //循环遍历查找文件和文件夹
-
{
-
if (fileData.cFileName[0] == '.') //当前目录或者上一目录,cFileName是文件名,cFileName[0]为第一个字符
-
{
-
continue;
-
}
-
if (fileData.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY ) //如果是目录
-
{
-
//cout<<"!!!!!!!!!!!!!"<<endl; //分割标示
-
//cout<<fileData.cFileName<<"***"<<endl;
-
//mapFile.insert(make_pair(fileData.cFileName, count)); // 把目录存入map
-
strcpy(curFind,lpPath);
-
strcat(curFind,fileData.cFileName);
-
strcat(curFind, "\\"); // 给文件夹加上\字符
-
fileFind(curFind, mapFile); // 继续递归查找
-
-
cout<<"!!!!!!!!!!!!!"<<endl;
-
}
-
//mapFile.insert(make_pair(fileData.cFileName, count)); //不判断则将全部文件存入map
-
int size= 0;
-
while (fileData.cFileName[size] != '\0' )
-
{
-
size ++;
-
}
-
if (fileData.cFileName[size-4] == '.' && fileData.cFileName[size-3]=='t'
-
&& fileData.cFileName[size-2]=='x' && fileData.cFileName[size-1]=='t') //判断是不是 .txt, 若
-
{
-
mapFile.insert(make_pair(fileData.cFileName, count)); // 把txt文件存入map
-
//cout<<fileData.cFileName<<endl;
-
}
-
-
}
-
}
-
int _tmain(int argc, _TCHAR* argv[])
-
{
-
map<string ,int> mapFile;
-
-
char filePath[] = "E:\\x\\";
-
fileFind(filePath,mapFile);
-
map<string, int>::iterator mapFileFind = mapFile.find("87686.txt");
-
if (mapFileFind != mapFile.end())
-
{
-
cout<< "It is right%%%%%%%%%"<<endl;
-
}
-
else
-
cout<<"It id false @@@@@@@@@"<<endl;
-
map<string, int>::iterator it = mapFile.begin();
-
for (; it != mapFile.end(); ++it)
-
{
-
cout<<it->first<<endl;
-
}
-
return 0;
-
}
运行如下:
!!!!!!!!!!!!!
!!!!!!!!!!!!!
!!!!!!!!!!!!!
!!!!!!!!!!!!!
!!!!!!!!!!!!!
It is right%%%%%%%%%
87686.txt
erwerwesfsdf.txt
fsgfg.txt
rtert.txt
sdfs.txt
xxx.txt
复件 (2) 87686.txt
复件 (2) erwerwesfsdf.txt
复件 (2) fsgfg.txt
复件 (2) rtert.txt
复件 (2) sdfs.txt
复件 (2) xxx.txt
复件 (3) 87686.txt
复件 (3) erwerwesfsdf.txt
如果运行不了,或者提示错误:错误 3 error C2664: “FindFirstFileW”: 不能将参数 1 从“char [260]”转换为“LPCWSTR” c:\documents and settings\zhangyongzhao\my documents\visual studio 2008\projects\finaltraservalfile\finaltraservalfile\finaltraservalfile.cpp 23
请将工程->属性->配置属性->常规->项目默认值->字符集 修改为“未设置”或“多字符字节”!
阅读(1525) | 评论(0) | 转发(0) |