HELP How to process multiple files in C++

Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
4 replies · 3K views
aLostProgramm
Messages
2
Reaction score
0
HELP! How to process multiple files in C++

I have been bashing my head against my desk in my cubical trying to figure this out. I have approximately 500 files I would like to read in, one at a time, into a C++ program, do my processing, and send the results to a new file. I can do the processing just fine, but I can't increment the files. Below is what I have:

Code:
#include <iostream>
#include <iomanip>
#include <fstream>

using namespace std;

int main()
{
  ifstream infile;
  ofstream outfile;

  float temp1,temp2;

  infile.open ("bTemp5.txt");
  outfile.open ("finalBtemp5.txt");

  while (!infile.eof())
    {
      infile >> temp1 >> temp2;
      temp1 = (temp1/100)+100;
      temp2 = (temp2/100)+100;
      outfile << temp1 << ' ' << temp2<<endl;
    }

  infile.close();
  outfile.close();

  return 0;

}
But instead of the highlighted 5's, I'd like it to be incremented, i.e. bTemp1.txt, bTemp2.txt, etc. Setting up the loop won't be a problem, I just need a quick, easy way to increment the files so I don't have to run the program once, change the program, run again... 500 times. I just want to send it through the loop.

Thanks in advance for a prompt response.
 
Physics news on Phys.org


How about:

Code:
#include <iostream>
#include <iomanip>
#include <fstream>

using namespace std;

int main()
{
  for (int i = 0; i < 500; ++i)
  {
    char infilename[256];
    char outfilename[256];
    sprintf(infilename, "bTemp%03d.txt", i);
    sprintf(outfilename, "finalBtemp%03d.txt", i);

    ifstream infile(infilename);
    ofstream outfile(outfilename);

    float temp1,temp2;

    while (infile >> temp1 >> temp2)
    {
      temp1 = (temp1/100)+100;
      temp2 = (temp2/100)+100;
      outfile << temp1 << ' ' << temp2<<endl;
    }
  }

  return 0;

}
 


Secret programming technique -- breaking a larger problem into smaller parts!

You needed to stop thinking "how can I open these 500 files" and you needed to start thinking "how can I create 500 strings of a particular form?"

(but, for the record, when asking others for help, you should mention the full problem even if you are asking for help on one of these smaller problems)
 


On unix, write a shell script that works through the file names (selected using wildcards) and runs your progam 500 times.

That way, you don't have to waste time writing code to do the special case of filenames in a particular format, when the Unix shells can already handle the general case.