I used to run a calculation by reading from 1 txt file ("1_Hello.txt"), calculate and output by functions, and write the output into a new txt file.
But now I have 5000 txt files ("1_Hello.txt" to "5000_Hello.txt"). I want to read all 5000 txt files, calculate each txt file by functions ( variable "a" and vector "v"), and write the output of these 5000 files into a new txt file and a new excel file that contains calculated results of all 5000 input files.
Input format: id x y z
Ex: 1 9 7 5
Wanted output format: id x y z add() int_vector()
Ex: 1 9 7 5 5.5 123
How can I read 5000 txt files and write the calculated results from functions into new txt and excel files?
Any help would be appreciated.
double add(){
// do something
}
void output_vector(std::vector<int> &v) {
// do something
}
int main() {
std::vector<int> v;
double a;
ifstream in("1_Hello.txt");
in.close();
a=add();
output_vector(v);
return 0;
}
Here is some very simple and incomplete code that might help along the way:
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
int main(int argc, char* argv[]) {
/* define some vectors to store the data in */
std::vector<int> id_vec;
std::vector<int> x_vec;
std::vector<int> y_vec;
std::vector<int> z_vec;
std::vector<double> calc_1_vec;
std::vector<double> calc_2_vec;
for (int i = 1; i < 5001; ++i) {
std::string file_name = std::to_string(i) + std::string("_hello.txt");
std::ifstream input_file (file_name);
if (input_file.is_open()) {
/* read whatever is in the file, maybe in a loop if there is more stuff in it */
/* then close it */
input_file.close();
/* parse the input line and store the values in some variables */
/* calculate whatever it is that you need to calculate */
/* then store the calculated values in the vectors */
/* also store the read values in the vectors */
}
else {
std::cout << "could not open file" << std::endl;
}
}
/* sort the vectors according to your needs */
/* make sure that zou change the other vectors accordingly */
/* so if you switch the 3. and the 4. index in the ID vector */
/* then also switch those in the other vectors */
/* open up the output file and write the vectors into the files */
}
And of course there are better solutions, like using std::filesystem to read all files in a directory that match a certain pattern.
Another improvement would be to only have one vector and define a struct that you store in that vector. This struct then has the ID, X, Y, Z and calculated fields. Then you could use some sort function from the standard library. The you could have member functions that handle the calculations, printing, etc.
struct data {
int id;
int x;
int y;
int z;
double calc_1;
double calc_2;
};
Then later simply:
std::vector<data> data_vec;