c++ 得到指定目录下指定文件名 windows vs2010

来源:互联网 发布:自动化测试与python 编辑:程序博客网 时间:2024/06/05 14:44

c++ 得到指定目录下指定文件名方法颇多,网上寻找总结有:

1. 主要思路是使用第三方库 dirent.h 文件来完成

C/C++ 获取目录下的文件列表信息

库文件下载点这里

数据结构:

struct dirent{    long d_ino;                 /* inode number 索引节点号 */    off_t d_off;                /* offset to this dirent 在目录文件中的偏移 */    unsigned short d_reclen;    /* length of this d_name 文件名长 */    unsigned char d_type;        /* the type of d_name 文件类型 */        char d_name [NAME_MAX+1];   /* file name (null-terminated) 文件名,最长255字符 */} struct __dirstream  {    void *__fd;                        /* `struct hurd_fd' pointer for descriptor.  */    char *__data;                /* Directory block.  */    int __entry_data;                /* Entry number `__data' corresponds to.  */    char *__ptr;                /* Current pointer into the block.  */    int __entry_ptr;                /* Entry number `__ptr' corresponds to.  */    size_t __allocation;        /* Space allocated for the block.  */    size_t __size;                /* Total valid data in the block.  */    __libc_lock_define (, __lock) /* Mutex lock for this structure.  */  };typedef struct __dirstream DIR;

stackoverflow示例

DIR *dir;struct dirent *ent;if ((dir = opendir ("c:\\src\\")) != NULL){/* print all the files and directories within directory */    while ((ent = readdir (dir)) != NULL)    {        printf ("%s\n", ent->d_name);    }    closedir (dir);}else{    /* could not open directory */    perror ("");    return EXIT_FAILURE;}


博客示例

#include <sys/types.h>#include <dirent.h>#include <unistd.h>#include <stdio.h>int main(){    DIR    *dir;    struct    dirent    *ptr;    dir = opendir("."); ///open the dir    while((ptr = readdir(dir)) != NULL) ///read the list of this dir    {        #ifdef _WIN32            printf("d_name: %s\n", ptr->d_name);        #endif        #ifdef __linux            printf("d_type:%d d_name: %s\n", ptr->d_type,ptr->d_name);        #endif    }    closedir(dir);    return 0;}


2. 主要思路是利用 boot filesystem module来完成。如果是交叉平台上,最好的方法是使用库来完成。

以下摘自stackoverflow:

给定一个路径和文件名,以下函数迭代地在该目录和该目录下的子目录中搜索该文件,返回一个布尔值,和如果成功找到的文件的路径。

bool find_file( const path & dir_path,         // in this directory,                const std::string & file_name, // search for this name,                path & path_found )            // placing path here if found{  if ( !exists( dir_path ) ) return false;  directory_iterator end_itr; // default construction yields past-the-end  for ( directory_iterator itr( dir_path );        itr != end_itr;        ++itr )  {    if ( is_directory(itr->status()) )    {      if ( find_file( itr->path(), file_name, path_found ) ) return true;    }    else if ( itr->leaf() == file_name ) // see below    {      path_found = itr->path();      return true;    }  }  return false;}


3. 主要思路是使用io.h提供的 handle_File =_findfirst( filespec, &fileinfo) 与 _findnext( handle_File, &fileinfo) 函数完成。

其中 handle_File 是文件句柄

filespec 是指定文件特性

fileinfo 是装有文件信息的结构体

函数名称:_findfirst
函数功能:搜索与指定的文件名称匹配的第一个实例,若成功则返回第一个实例的句柄,否则返回-1L
函数原型:long _findfirst( char *filespec, struct _finddata_t *fileinfo );
头文件:io.h


函数名称:_findnext

函数功能:搜索与_findfirst函数提供的文件名称匹配的下一个实例,若成功则返回0,否则返回-1

函数原型:int _findnext( intptr_t handle, struct _finddata_t *fileinfo);

头文件:io.h


程序举例(http://baike.baidu.com/view/1186290.htm)

#include<io.h>#include<stdio.h>int main(){    long Handle;    struct _finddata_t FileInfo;    if((Handle=_findfirst("D:\\*.txt",&FileInfo))==-1L)        printf("没有找到匹配的项目\n");    else    {        printf("%s\n",FileInfo.name);        while(_findnext(Handle,&FileInfo)==0)            printf("%s\n",FileInfo.name);        _findclose(Handle);    }    return 0;}

相关博客有:

使用_findfirst和_findnext遍历目录

Window文件目录遍历 和 WIN32_FIND_DATA 结构

使用C++获取文件夹中所有文件名(windows环境)

c++ 遍历目录下文件 该文将文件目录遍历封装成类

4. 一个函数就够,不需要三方库

函数如下:

#include <Windows.h>vector<string> get_all_files_names_within_folder(string folder){    vector<string> names;    char search_path[200];    sprintf(search_path, "%s*.*", folder.c_str());    WIN32_FIND_DATA fd;     HANDLE hFind = ::FindFirstFile(search_path, &fd);     if(hFind != INVALID_HANDLE_VALUE)     {         do         {             // read all (real) files in current folder            // , delete '!' read other 2 default folder . and ..            if(! (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) )             {                names.push_back(fd.cFileName);            }        }while(::FindNextFile(hFind, &fd));         ::FindClose(hFind);     }     return names;}

以上不少方法参见此贴

实践过方法3,并简化为只访问指定目录下指定文件(不访问字目录):

#ifndef GETDIRECTORY_REDUCED_H#define GETDIRECTORY_REDUCED_H#include <stdlib.h>#include <direct.h>#include <string>#include <io.h>class CBrowseDir{private:char m_szDir[_MAX_PATH];int m_nFileCount;   //保存文件个数long int handle_File;public:CBrowseDir();//设置初始目录为dir,指定文件filespec,如果返回false,表示目录不可用bool SetDir(const char *dir, const char *filespec);//遍历目录dir下由filespec指定的文件,不访问子目录,如果返回false,表示中止遍历文件bool BrowseDir(const char *filespec);//每次调用给出该目录下的下一个指定文件的路径,成功返回truebool CBrowseDir::NextFile(std::string &);//返回文件个数int GetFileCount();};#endif

#include <stdlib.h>#include <direct.h>#include <string>#include <io.h>#include <stdio.h>#include <iostream>#include "GetDirectory_Reduced.h"using namespace std;CBrowseDir::CBrowseDir(){//用当前目录初始化m_szDir_getcwd(m_szDir,_MAX_PATH);//如果目录的最后一个字母不是'\',则在最后加上一个'\'int len=strlen(m_szDir);if (m_szDir[len-1] != '\\'){m_szDir[len]='\\';m_szDir[len+1]='\0';}//strcat(m_szDir,"\\");m_nFileCount=0;}bool CBrowseDir::SetDir(const char *dir, const char *filespec){//先把dir转换为绝对路径if (_fullpath(m_szDir,dir,_MAX_PATH) == NULL)return false;//判断目录是否存在,并转到指定目录m_szDir下if (_chdir(m_szDir) != 0)return false;//如果目录的最后一个字母不是'\',则在最后加上一个'\'int len=strlen(m_szDir);if (m_szDir[len-1] != '\\'){m_szDir[len]='\\';m_szDir[len+1]='\0';}//strcat(m_szDir,"\\");_chdir(m_szDir);//转换到指定目录下_finddata_t fileinfo;handle_File=_findfirst(filespec,&fileinfo);//首先查找dir中符合要求的文件if(handle_File==-1)return false;return true;}bool CBrowseDir::BrowseDir(const char *filespec){_chdir(m_szDir);//首先查找dir中符合要求的文件long hFile;_finddata_t fileinfo;if ((hFile=_findfirst(filespec,&fileinfo)) != -1){do{//检查如果不是子文件夹,则进行处理if (!(fileinfo.attrib & _A_SUBDIR)){string filename(m_szDir);//用string来处理,避免strcpy、strcat带来的warningfilename+=fileinfo.name;cout << filename << endl;m_nFileCount++;//文件数加1}} while (_findnext(hFile,&fileinfo) == 0);_findclose(hFile);}return true;}bool CBrowseDir::NextFile(string &nextfilename){_finddata_t fileinfo;while(_findnext(handle_File,&fileinfo) == 0){//检查如果不是子文件夹,则进行处理if((fileinfo.attrib & _A_SUBDIR))continue;string filename(m_szDir);//用string来处理,避免strcpy、strcat带来的warningfilename+=fileinfo.name;cout << filename << endl;nextfilename=filename;m_nFileCount++;//文件数加1return true;}_findclose(handle_File);return false;}//返回文件个数int CBrowseDir::GetFileCount(){return m_nFileCount;}


0 0
原创粉丝点击