2015-06-12 6 views
0

Я попытался прочитать все имена файлов каталога в массиве, и мой код успешно добавляет целые имена файлов в массив. Тем не менее, что мне нужно,Как читать конкретные имена файлов каталога в массиве

1-й получает, не все из них, только имена файлов spesific, которые заканчиваются как .cpp или .java. Это должно быть сделано в этой части, и мои сравнения не сработали. Как я могу это сделать ?

DIR   *dir; 
struct dirent *dirEntry; 
vector<string> dirlist; 

while ((dirEntry = readdir(dir)) != NULL) 
      { 
        //here 
         dirlist.push_back(dirEntry->d_name); 
      } 

2dn ​​один получает местоположение каталога от пользователя. Я тоже не мог этого сделать, он работает только, если я пишу адрес местонахождения, как я могу получить местоположение от пользователя для получения файлов?

dir = opendir(//here); 
+1

Какие типы, какое сравнение не работает? – BeyelerStudios

+0

Какую ОС вы программируете? Это зависит от платформы. – user2079303

+0

Извините, что я не опубликовал его. тип dirlist - это вектор . И работать над окнами достаточно для меня. – donanimsal

ответ

0

Я думаю, что это будет работать для вашего случая,

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); 
} 

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

+0

Thanx man, я искал strstr (hFile-> d_name, ".txt") эту часть: D – donanimsal

0
#include <iostream> 
#include "boost/filesystem.hpp" 

using namespace std; 
using namespace boost::filesystem; 

int main(int argc, char *argv[]) 
{ 
    path p (argv[1]); 

    directory_iterator end_itr; 

    std::vector<std::string> fileNames; 
    std::vector<std::string> dirNames; 


    for (directory_iterator itr(p); itr != end_itr; ++itr) 
    { 
    if (is_regular_file(itr->path())) 
    { 
     string file = itr->path().string(); 
     cout << "file = " << file << endl; 
     fileNames.push_back(file); 
    } 
    else if (is_directory(itr->path())) 
    { 
     string dir = itr->path().string(); 
     cout << "directory = " << dir << endl; 
     dirNames.push_back(dir); 
    } 
    } 
} 
Смежные вопросы