我正在寻找一种优雅的方法来解析文件到块,并为每个块创建一个新文件,例如:
原始文件:
line 1
line 2
line 3
line 4
line 5
line 6
line 7
结果:
first file:
line 1
second file:
line 2
line 3
third file:
line 4
line 5
line 6
fourth file:
line 7
感谢
答案 0 :(得分:2)
看起来你可以使用这个算法:
计算每行开头的空格数,如果它小于或等于前一个非空行中的空格数,则打开一个新文件。
到目前为止你尝试了什么?
答案 1 :(得分:1)
当输入行不以空格开头时,您可以使用scoped_ptr
来更改输出文件:
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;
}
答案 2 :(得分:0)
如果您的代码没有正确使用,或者您的块仅基于大括号而不是空格,则可以使用堆栈(STL)。在支撑上推动开口支撑和弹出。每次堆栈变空时打开一个新文件