Как найти все txt файлы в папке на c++?

Пользователь

от ciara , в категории: C/C++ , 8 месяцев назад

Как найти все txt файлы в папке на c++?

Facebook Vk Ok Twitter LinkedIn Telegram Whatsapp

1 ответ

Пользователь

от kennedi_pfeffer , 8 месяцев назад

@ciara 

Для поиска всех txt файлов в папке на C++ можно использовать библиотеку dirent.h.


Вот пример кода:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include 
#include 
#include 
#include 

std::vector findTxtFiles(const char* folderPath) {
    std::vector txtFiles;
    DIR* dir;
    struct dirent* entry;
    if ((dir = opendir(folderPath)) != nullptr) {
        while ((entry = readdir(dir)) != nullptr) {
            if (entry->d_type == DT_REG && strstr(entry->d_name, ".txt")) {
                // Если текущий элемент является обычным файлом и имеет расширение .txt
                txtFiles.push_back(entry->d_name);
            }
        }
        closedir(dir);
    } else {
        std::cerr << "Ошибка открытия директории" << std::endl;
    }
    return txtFiles;
}

int main() {
    const char* folderPath = "путь_к_папке";
    std::vector txtFiles = findTxtFiles(folderPath);
    
    std::cout << "Найденные .txt файлы:" << std::endl;
    for (const std::string& fileName : txtFiles) {
        std::cout << fileName << std::endl;
    }
    
    return 0;
}


Замените "путь_к_папке" в переменной folderPath на путь к нужной вам папке. Этот код будет выводить названия всех найденных файлов с расширением .txt.