Search code examples
c++parsingfileblock

How to Parse A file to block in C++


I am looking for an elegant way to parse a file to blocks and for each block create a new file , for example :

original file:

line 1
line 2
 line 3

line 4
 line 5
   line 6
line 7

result:

first file:
line 1

second file:
line 2
 line 3

third file:
line 4
 line 5
   line 6

fourth file:
line 7

thanks


Solution

  • You could use scoped_ptrs to change the output file when the input line does not begin with whitespace:

    std::ifstream in("/your/input/file");
    boost::scoped_ptr<std::ofstream> out(NULL)
    int out_serial = 0;
    std::string line;
    while(std::getline(in, line))
    {
        // test: first character non blank
        if(! line.empty() && (line.at(0) != ' ' && line.at(0) != '\t'))
        {
            std::ostringstream new_output_file;
            new_output_file << "/your/output/file/prefix_" << out_serial++;
            out.reset(new std::ofstream(new_output_file.str()));
        }
        if(out.get() != NULL) (*out) << line << std::endl;
    }