Farnaz76
Farnaz76

Reputation: 11

Read multiple files in directory for editing and writing into another set of files

I am newbie in C++ and appreciate if someone could help me figure this out. I wrote the following code and it works fine but I need to repeat it for many files in the same directory. It reads 0.txt line by line, removes lines of strings of characters if found and writes the rest of the lines which are only numbers into another file named 0.dat. I need to repeat this for multiple files (0.txt,1.txt....100.txt) in the same directory.

    #include <iostream>
    #include <fstream>
    #include <string>
    int main()
    {
    std::ifstream in;
    std::ofstream out;
    in.open("0.txt");
    out.open("0.dat");
    if(in.is_open() && out.is_open()){
         while(std::getline(in, line)){
                if(line.find(" No.")==line.npos){
                         out << line << "\n";
                         std::cout << "line is:\t" << line<<"\n";
                }
          }
    }

    in.close();
    out.close();
    return 0;
    }

How can I create a loop to read 100 ".txt" files and write them into 100 ".dat" files with correct name reference?

Upvotes: 0

Views: 547

Answers (1)

renspaceyi
renspaceyi

Reputation: 96

It's simple, really. First thing we will do is make that stuff you've already written into a function. But not before making some edits. It should do exactly the same thing your code does, but with better practices!

void readAndWrite(std::string in_name, std::string out_name)
{
    std::ifstream in{in_name};
    std::ofstream out{out_name};
    std::string line;

    if (!in.is_open() || !out.is_open())
        return;

    while (std::getline(in, line)) {
        if (line.find(" No.") == line.npos) {
            out << line << "\n";
            std::cout << "line is:\t" << line<<"\n";
        }
    }
}

Then we just need to call it 100 times with our file names. I'll assume that your files are named like "0.txt", "1.txt", ... and so on. We can do this using std::to_string(), a function which, as the name implies, changes things to std::strings. In our case, we'll be changing ints to std::strings. This is one way to do it. (this will be in main):

#include <string>
...
for (int i = 0; i < 100; ++i) {
    std::string fname = std::to_string(i);
    readAndWrite(fname + ".txt", fname + ".dat");
}

And that should do it!

Upvotes: 2

Related Questions