Hello dear: this is my first time here and really appreciate some help.
I have this files in my folder:
name1.dat
name2.dat
name3.dat
name4.dat
...
name{i}.dat
I'd like to read them using function.
Thank you in advance.
Hello dear: this is my first time here and really appreciate some help.
I have this files in my folder:
name1.dat
name2.dat
name3.dat
name4.dat
...
name{i}.dat
I'd like to read them using function.
Thank you in advance.
 
    
     
    
    Like this, you didn't say how many files you have so I just assumed you have 100.
#include <fstream>
#include <string>
for (int i = 1; i <= 100; ++i)
{
    std::string name = "name" + std::to_string(i) + ".dat";
    std::ifstream file(name);
    ...
}
 
    
    Here you have some C++20 code that archives that using parallel threads with a few lines of code.
// Headers required <algorithms> <execution> <sstream> <fstream> <vector> <string>
std::string open_and_read_file(const std::string path)
{
    std::ifstream file(path);
    return std::string(std::istreambuf_iterator<char>(file),
                       std::istreambuf_iterator<char>());
}
std::vector<std::string> read_files(const std::vector<std::string>& file_paths)
{
    std::vector<std::string> readed_files;
    std::for_each(std::execution::par,
        file_paths.begin(),file_paths.end(),
        [&](const auto& file_path)
        {
            readed_files.push_back(open_and_read_file(file_path));
        });
    return readed_files;
}
int main()
{
    auto readed_files = read_files({"name1.dat","name2.dat","name3.dat"});
    return 0;
}
Compile using this:
g++ -std=c++20 -ltbb main.cpp -o main.out
-ltbb is required to the multithreading
