简体   繁体   中英

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:

#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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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