简体   繁体   English

C++如何一一读取目录下的所有文件

[英]How to read all files of directory one by one in C++

I want to read all the files of a directory and print the words in it, all I've done is to store the names of the files to a string array but now how would I do that...我想读取目录的所有文件并打印其中的单词,我所做的就是将文件名存储到字符串数组中,但现在我该怎么做...

my code for storing file names:我用于存储文件名的代码:

struct dirent *contents;
DIR *dir;
dir= opendir((char*)"text files");
DIR *op;
op= opendir((char*)"text files");
if(!dir){
    cout<<"The given directory is not found";
}
else {
    string *arr;
    int count;
    int i=0;
    while ((readdir(op)) != NULL){
        count++;
    }//for the size array equivalent to number of txt files in directory
    count=count-2;
    arr=new string[count];
    while ((contents = readdir(dir)) != NULL) {
        string name = contents->d_name;
        if (name != "."&&name!="..") {
            arr[i]=name;
            i++;
        }
    }
    cout<<"\t*The list of files are*"<<endl;
    for(int j=0;j<count;j++){
        cout<<arr[j]<<endl;
    }
}}

Any guidance任何指导

The simplest solution to your problem, as I can understand it, is to use one of the loops from main below:据我所知,解决您的问题的最简单方法是使用以下main循环之一:

#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;

int main()
{
    // print all files from the current directory and below
    for(auto& p: fs::recursive_directory_iterator(fs::current_path()))
        std::cout << p.path() << '\n';
    // print all files from the current directory
    for(auto& p: fs::directory_iterator(fs::current_path()))
        std::cout << p.path() << '\n';
}

This is C++17 standard code.这是 C++17 标准代码。 This is modern code.这是现代代码。 If you went as far as to tackle the problem with the C interface, you'll know what to do with these loops.如果您使用 C 接口解决问题,您就会知道如何处理这些循环。

The (technical) documentation of the filesystem standard library is, for example, here: https://en.cppreference.com/w/cpp/filesystem This library has all you need, including utilities to tell ordinary files from symbolic links, directory names etc. Paths can be easily converted to std::string s via their string family member functions, see: https://en.cppreference.com/w/cpp/filesystem/path文件filesystem标准库的(技术)文档是,例如,这里: https : //en.cppreference.com/w/cpp/filesystem这个库有你需要的一切,包括从符号链接、目录中告诉普通文件的实用程序名称等。路径可以通过其string族成员函数轻松转换为std::string s,请参阅: https : //en.cppreference.com/w/cpp/filesystem/path

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM