I have a txt file that has 500,000 lines, and each line has 5 columns. I want to read data from this file and write it into different 5000 txt files that have 100 lines each, starting from the first line to the last of the input file. Also, the filename is output with the order number, say "1_Hello.txt", which has the 1st line to 100th line, "2_Hello.txt", which has the 101st line to 200th line, and so on, until "5000_Hello.txt", which has the 499901st line to 500000th line.
I used to run the following code to write files that are less than 10 files. But How can I write it in the case of 5000 text files? Any help would be appreciated.
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main() {
vector<string> VecData;
string data;
ifstream in("mytext.txt");
while (in >> data) {
VecData.push_back(data);
}
in.close();
ofstream mynewfile1;
char filename[]="0_Hello.txt";
int i, k=0, l=0;
while(l<VecData.size()){
for(int j='1';j<='3';j++){
filename[0]=j;
mynewfile1.open(filename);
for( i=k; i<k+((int)VecData.size()/3);i+=5){
mynewfile1<<VecData[i]<<"\t";
mynewfile1<<VecData[i+1]<<"\t";
mynewfile1<<VecData[i+2]<<"\t";
mynewfile1<<VecData[i+3]<<"\t";
mynewfile1<<VecData[i+4]<<endl;
}
mynewfile1.close();
l=i;
k+=(int)VecData.size()/3;
}
}
cout<<"Done\n";
return 0;
}