How to get list of files with a specific extension in a given folder?

前端 未结 6 1880
孤街浪徒
孤街浪徒 2020-11-27 03:29

I want to get the file names of all files that have a specific extension in a given folder (and recursively, its subfolders). That is, the file name (and extension), not th

6条回答
  •  一生所求
    2020-11-27 04:15

    On windows you do something like this:

    void listFiles( const char* path )
    {
       struct _finddata_t dirFile;
       long hFile;
    
       if (( hFile = _findfirst( path, &dirFile )) != -1 )
       {
          do
          {
             if ( !strcmp( dirFile.name, "."   )) continue;
             if ( !strcmp( dirFile.name, ".."  )) continue;
             if ( gIgnoreHidden )
             {
                if ( dirFile.attrib & _A_HIDDEN ) continue;
                if ( dirFile.name[0] == '.' ) continue;
             }
    
             // dirFile.name is the name of the file. Do whatever string comparison 
             // you want here. Something like:
             if ( strstr( dirFile.name, ".txt" ))
                printf( "found a .txt file: %s", dirFile.name );
    
          } while ( _findnext( hFile, &dirFile ) == 0 );
          _findclose( hFile );
       }
    }
    

    On Posix, like Linux or OsX:

    void listFiles( const char* path )
    {
       DIR* dirFile = opendir( path );
       if ( dirFile ) 
       {
          struct dirent* hFile;
          errno = 0;
          while (( hFile = readdir( dirFile )) != NULL ) 
          {
             if ( !strcmp( hFile->d_name, "."  )) continue;
             if ( !strcmp( hFile->d_name, ".." )) continue;
    
             // in linux hidden files all start with '.'
             if ( gIgnoreHidden && ( hFile->d_name[0] == '.' )) continue;
    
             // dirFile.name is the name of the file. Do whatever string comparison 
             // you want here. Something like:
             if ( strstr( hFile->d_name, ".txt" ))
                printf( "found an .txt file: %s", hFile->d_name );
          } 
          closedir( dirFile );
       }
    }
    

提交回复
热议问题