Search code examples
c++vectorifstream

c++ write vector elements to split files


Given I have a vector<string> lines which contain all the lines read from a file, how can i then write the contents of the vector back to a file except split it by x many lines per file. I'm more so stuck with the chunking problem rather than writing back to file. An example would be if

int offset = 10000;
std::vector<std::string> lines(27000);

...assuming lines has been initialized with lines

given the above I should have

file1 : 10000

file2 : 10000

file3: 7000


Solution

  • Simple enough, you just need a loop and an if statement.

    ofstream output;
    string filename = "filename";
    int fileNum = 0;
    
    for(int i = 0; i < vec.size(); ++i){
        if(i % 10000 == 0){
            if(output.is_open()) output.close();
            output.open(filename + to_string(++fileNum));
        }
        output << vec.at(i);
    }
    
    output.close();
    

    That will save files in "filename1", "filename2", and "filename3" for a 27000 line file.

    Disclaimer: Written free hand: may contain syntax errors.