C + + gets all the file names under the folder

Source: Internet
Author: User
Tags strcmp

Get all the filenames under the folder is a common feature, today once again have this demand, all on the internet to find a lot, and write down for later use.

Original: http://blog.csdn.NET/cxf7394373/article/details/7195661

Original: http://qiaoxinwang.blog.163.com/blog/static/86096452010612139172/

Header files: #include <io.h>

1 char * filePath = "d:\\sample";

1vector<string>files; 2   3 ////Get all files under this path4 getFiles (FilePath, files); 5   6 Charstr[ -]; 7 intSize =files.size (); 8  for(inti =0; I < size;i++)  9 {  TenCout<<files[i].c_str () <<Endl;  One}
1 voidGetFiles (stringPath, vector<string>&files)2 {  3     //file handle4     Longhfile =0; 5     //File Information6     struct_finddata_t FileInfo; 7     stringp; 8     if(hfile = _findfirst (p.assign (Path). Append ("\\*"). C_str (), &fileinfo))! =-1)  9     {  Ten          Do   One         {   A             //in the case of a directory, the iteration -             //if not, join the list -             if((Fileinfo.attrib &_a_subdir))  the             {   -                 if(strcmp (Fileinfo.name,".") !=0&& strcmp (Fileinfo.name,"..") !=0)   -GetFiles (p.assign (Path). Append ("\\"). Append (Fileinfo.name), files);  -             }   +             Else   -             {   +Files.push_back (p.assign (Path). Append ("\\"). Append (Fileinfo.name));  A             }   at} while(_findnext (hfile, &fileinfo) = =0);  - _findclose (hfile);  -     }   -}
Use of _finddata_t

So how exactly do you find files? We need a struct and several functions that you might not be familiar with. These functions and structs are in the header file of <io.h>, struct _finddata_t, functions are _findfirst, _findnext, and _fineclose. Specifically how to use, I will speak slowly ~
First of all, the structure of the bar ~ struct _finddata_t, the structure is used to store various information of the file. To tell the truth, this structure of the specific definition code, I did not find, but fortunately, the document inside the _find there are more detailed member variable introduction. I basically translated the document:


unsigned atrrib: the location where the file properties are stored. It stores a unsigned unit that represents the properties of a file. The file attributes are expressed in bits, mainly in the following: _a_arch (archive), _a_hidden (hidden), _a_normal (normal), _a_rdonly (read-only), _a_subdir (folder), _a_system (System).

These are macros defined in <io.h> and can be used directly, but the meaning of this is an unsigned integer (except that the integer should be a power of 2, guaranteeing only one is 1, while the other bit is 0). Since it is a bit representation, then when a file has multiple attributes, it is often a bit or a way to get a synthesis of several attributes. For example read-only + hide + system Properties, should be: _a_hidden | _a_rdonly | _a_system.
time_t time_create: time_t Here is a variable type (Long integer?). Equivalent to a long int?), used to store the time, we do not have to ignore it, as long as we know that the time_create variable is used to store the file creation time can be.
time_t time_access : The time when the file was last accessed.
time_t time_write : The time when the file was last modified.
_fsize_t Size : The file sizes. The _fsize_t here should be equivalent to the unsigned integer, representing the number of bytes in the file.
Char Name[_max_fname] : The file name of the file. The _max_fname here is a constant macro, which is defined in the <stdlib.h> header file, which represents the maximum length of the file name.
In this, we can extrapolate, struct _finddata_t, the approximate definition is as follows:

 1  struct   _finddata_t  2  { 3   unsigned attrib;  4   time_t time_create;  5   time_t time_access;  6   time_t time_write;  7   _fsize_t size;  8  char   n Ame[_max_fname];  9 }; 

As I said earlier, this structure is used to store file information, so how to "save" the file information of a hard disk file into the memory space represented by this structure? This depends on the combination of _findfirst, _findnext and _fineclose three functions.

Let's start by introducing some of these three functions ...

Long _findfirst (char *filespec, struct _finddata_t *fileinfo);

Return value: If the lookup succeeds, a long unique lookup handle (that is, a unique number) is returned. This handle will be used in the _findnext function. If it fails, it returns-1.

Parameters:

filespec: A string that identifies the file, which can support wildcard characters. For example: *.C, indicates all files with the suffix C under the current folder.

FileInfo: This is the pointer to the struct that holds the file information. The struct must be declared before calling this function, but without initialization, as long as the memory space is allocated. After the function succeeds, the function will put the information of the found file into the struct.

int _findnext (long handle, struct _finddata_t *fileinfo);

Return value: Returns 1 if 0 is returned successfully.

Parameters:

Handle: The handle returned by the _findfirst function.

FileInfo: A pointer to the file information structure body. When the file is found, the function places the file information into the structure.

int _findclose (long handle);

Return value: Successfully returned 0, failure returned-1.

Parameters:

handle: The _findfirst function returns the handle returned.

You see here, you can probably guess what? First use _findfirst to find the first file, if successful, call the _findnext function with the returned handle to find other files, when the search is complete, use the _findclose function to end the search. Well, yes, that's the right idea. Let's follow this idea to write a program that finds all EXE executables under the C:\WINDOWS folder.

1#include <stdio.h>2#include <io.h>3 4 5         Const Char*to_search="C:\\windows\\*.exe";//to find a file that supports wildcard characters6 7 8         intMain ()9         {Ten              LongHandle//Handle for lookup One              struct_finddata_t FileInfo;//structure of file information AHandle=_findfirst (To_search,&fileinfo);//first-time lookup -              if(-1==handle)return-1; -printf"%s\n", fileinfo.name);//print out the file names of the found files the               while(!_findnext (Handle,&fileinfo))//Loop to find other compliant files, knowing that no other is found -              { -printf"%s\n", fileinfo.name); -             } +_findclose (handle);//don't forget to close the handle -System"Pause"); +              return 0; A}


Of course, the search for this file is done in the specified path, how to traverse the hard disk, and find the file on the entire hard drive? You can search the web for recursive traversal of files, and so on, there is no further introduction.


A careful friend might notice that I used a system function at the end of the program. This has nothing to do with the program itself, and the use of the GetChar () function is the same as previously introduced to you, just to pause, so we can see the output from the command prompt. However, the system function itself is a very powerful function. You can check out MSDN. To put it simply, it is a C language and operating system platform, you can pass this function in the program, to the operating system to pass command commands

More examples:

The main use of the following header files (classes): IO.h, FStream, String.

First, read all the folders and file names under a given path, with the full path. The implementation code is as follows:

void Getallfiles (string path, vector<string>& files)  {    //file handle    long  hfile  =  0;    File information    struct _finddata_t fileinfo;    string P;    if (hfile = _findfirst (p.assign (Path). Append ("\\*"). C_str (), &fileinfo))! =-1)    {      do      {         if ( Fileinfo.attrib & _a_subdir)        {          if (strcmp (Fileinfo.name, ".")! = 0 && strcmp (fileinfo.name, "...")! = 0)          {          files.push_back (p.assign (Path). append ("\ \"). Append (Fileinfo.name));           Getfilesall (p.assign (Path). append ("\ \"). Append (Fileinfo.name), files);}       }        else        {          files.push_back (p.assign (Path). append ("\ \"). Append (Fileinfo.name));}      } while (_findnext (hfile, &fileinfo) = = 0);      _findclose (hfile);    }  

The function has two parameters, the first is a path string (string type, preferably an absolute path), and the second parameter is the folder and file name store variable (vector type, reference pass).
Call the format in the main function (and save the result in the file "AllFiles.txt", the total number of first actions):

char * FilePath = "E:\\yunshi";  vector<string> files;  char * distall = "AllFiles.txt"; Getfilesall (FilePath, files); Ofstream ofn (Distall); int size = Files.size ();  ofn<<size<<endl; for (int i = 0;i<size;i++)  {    ofn<<files[i]<<endl;  } ofn.close ();

Similarly, read only the current folder name under a given path (similar to the following, just give the function, call the case above):

void Getjustcurrentdir (string path, vector<string>& files)  {    //file handle    long  hfile  =  0;   File information    struct _finddata_t fileinfo;    string P;    if (hfile = _findfirst (p.assign (Path). Append ("\\*"). C_str (), &fileinfo))! =-1)    {      do      {         if ( Fileinfo.attrib & _a_subdir)        {          if (strcmp (Fileinfo.name, ".")! = 0 && strcmp (fileinfo.name, "...")! = 0)          {           files.push_back (fileinfo.name);           Files.push_back (p.assign (Path). append ("\ \"). Append (Fileinfo.name));}}       while (_findnext (hfile, &fileinfo) = = 0);      _findclose (hfile);    }  

Read only the current file name under a given path:

void Getjustcurrentfile (string path, vector<string>& files)  {    //file handle    long  hfile  =  0;    File information    struct _finddata_t fileinfo;    string P;    if (hfile = _findfirst (p.assign (Path). Append ("\\*"). C_str (), &fileinfo))! =-1)    {      do      {         if ( Fileinfo.attrib & _a_subdir))        {          ;       }        else        {          files.push_back (fileinfo.name);         Files.push_back (p.assign (Path). append ("\ \"). Append (Fileinfo.name));}       } while (_findnext (hfile, &fileinfo) = = 0);      _findclose (hfile);    }  

Read only all filenames under a given path (that is, files that contain the current directory and subdirectories):

void Getfilesall (string path, vector<string>& files)  {    //file handle    long  hfile  =  0;    File information    struct _finddata_t fileinfo;    string P;    if (hfile = _findfirst (p.assign (Path). Append ("\\*"). C_str (), &fileinfo))! =-1)    {      do      {         if ( Fileinfo.attrib & _a_subdir)        {          if (strcmp (Fileinfo.name, ".")! = 0 && strcmp (fileinfo.name, "...")! = 0)          {           //files.push_back (p.assign (Path). append ("\ \"). Append (Fileinfo.name));           Getfilesa (p.assign (Path). append ("\ \"). Append (Fileinfo.name), files);}       }        else        {          files.push_back (p.assign (Path). append ("\ \"). Append (Fileinfo.name));}      } while (_findnext (hfile, &fileinfo) = = 0);      _findclose (hfile);    }  

C + + gets all the file names under the folder

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.