-2

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.

cdecompilador
  • 178
  • 2
  • 9
TINA
  • 21
  • 4
  • Actually your problem is not clear can u plz elaborate it .Its hard to understand. – Aditya Shende Jun 12 '20 at 09:11
  • 1
    Any [good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) will show you how to create a string from smaller pieces. Look at [std::string](https://en.cppreference.com/w/cpp/string/basic_string), [std::to_string](https://en.cppreference.com/w/cpp/string/basic_string/to_string), [operator+](https://en.cppreference.com/w/cpp/string/basic_string/operator%2B). – molbdnilo Jun 12 '20 at 09:13

2 Answers2

2

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);
    ...
}
john
  • 85,011
  • 4
  • 57
  • 81
  • Thank you very much John I have around 55 files in Folder – TINA Jun 12 '20 at 15:07
  • Thank you very much John I have 55 files in Folder. But I got these error Function to_string(i) is not defined in current scope result_plot.c :46: – TINA Jun 12 '20 at 15:28
  • @TINA `std::to_string` is defined in the `` header file, but it is only available with C++11 or later. So if you are not seeing it you should enable C++11 on your compiler. – john Jun 12 '20 at 16:39
1

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

cdecompilador
  • 178
  • 2
  • 9