How to Parse A file to block in C++
I am looking f开发者_高级运维or 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
It looks like you could use this algorithm:
Count the number of spaces at the beginning of each line, if it's less than or equal to the number of spaces in the preceding non-empty line, open a new file.
What have you tried so far?
You could use scoped_ptr
s 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;
}
If your code is not properly intended or your blocks are only based on braces not spaces, you can use a stack(STL). Push on opening brace and Pop on closing brace. Open a new file each time the stack become empty
精彩评论