Adding spaces at end of every record in a file except the last two records

Hi friends, I am reading records from an external file to process them, but before processing them i need to make all records (except the last four) of equal length meaning all records should be padded with spaces and made of length 99 characters and also no spaces to be added to the last four records. Entire data then moves to a string for processing. The records that are being read are not necessarily of the same length. Please advise.
If the file is not huge (its contents can be held in memory):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <string>
#include <vector>
#include <fstream>

int main()
{
    const char* const srce_file_path = "myfile.txt" ;
    const char* const dest_file_path = "myfile.modified.txt" ;
    const std::size_t REC_SIZE = 99 ;
    const std::size_t TAIL_SIZE = 4 ;

    // 1. read the lines in the file into a vector
    std::vector<std::string> lines ;
    {
        std::ifstream file(srce_file_path) ;
        std::string str ;
        while( std::getline( file, str ) ) lines.push_back(str) ; // std::move(str)
    }

    // 2. resize lines (except the last TAIL_SIZE lines) to REC_SIZE
    if( lines.size() > TAIL_SIZE )
        for( std::size_t i = 0 ; i < ( lines.size() - TAIL_SIZE ) ; ++i )
            lines[i].resize( REC_SIZE, ' ' ) ;

    // 3. Write the padded lines into the destination file
    {
        std::ofstream file(dest_file_path) ;
        for( const std::string str : lines ) file << str << '\n' ;
    }
}
Entire data then moves to a string for processing.

Cannot be "huge" then.

If a file would be huge, then one could have a buffer for TAIL_SIZE + 1 lines.
Start reading to buffer.
When buffer is full, pad the first line, pop it out, and read next line in.
When read fails, flush the buffer out.
Topic archived. No new replies allowed.