码迷,mamicode.com
首页 > 编程语言 > 详细

文件搜索查找功能C++

时间:2015-02-02 18:01:22      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:

1.搜索指定文件夹下的文件名和路径

技术分享
#undef UNICODE  
       
#include <iostream>  
#include <string>  
#include <vector>  
#include <memory>  
#include <cstring>  
       
#include <windows.h>  
       
std::shared_ptr<std::vector<std::string> >  fileList(const std::string& folder_path)  
{  
    static std::shared_ptr<std::vector<std::string> >   
        folder_files(new std::vector<std::string>); //返回指针, 需要迭代使用  
       
    WIN32_FIND_DATA FindData;  
    HANDLE hError;  
       
    int file_count(0);  
    std::string file_path(folder_path); //路径名  
    std::string full_file_path; //全路径名   
       
    file_path.append("/*.*");  
    hError = FindFirstFile(file_path.c_str(), &FindData);  
    if (hError == INVALID_HANDLE_VALUE) {  
        std::cout << "failed to search files." << std::endl;  
        return nullptr;  
    }  
    while(FindNextFile(hError, &FindData))  
    {  
        //过虑".", "..", "-q"  
        if(0 == strcmp(FindData.cFileName, ".") ||   
            0 == strcmp(FindData.cFileName, "..") ||   
            0 == strcmp(FindData.cFileName, "-q"))  
        {  
            continue;  
        }  
       
        //完整路径  
        full_file_path.append(folder_path);  
        full_file_path.append("/");  
        full_file_path.append(FindData.cFileName);  
        ++file_count;  
       
        if (FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY){  
            //std::cout << file_count << " " << full_file_path << "<Dir>" << std::endl;  
            fileList(full_file_path);  
        }else{  
            folder_files->push_back(full_file_path);  
            //std::cout << file_count << " " << full_file_path << std::endl;  
        }  
        full_file_path.clear(); //清空目录  
    }  
    return folder_files;  
}  
       
int main(void)   
{  
    std::shared_ptr<std::vector<std::string> > folder_files;  
    folder_files = fileList("E:/bf");  
    if (folder_files) {  
        for (size_t i=0; i != folder_files->size(); ++i) {  
            std::cout << i+1 << " : " << (*folder_files)[i] << std::endl;  
        }  
    }  
    return 0;  
}
View Code

技术分享

文件搜索查找功能C++

标签:

原文地址:http://www.cnblogs.com/lwngreat/p/4268232.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!